Home > OS >  How to remove comma from each element of vector string
How to remove comma from each element of vector string

Time:09-23

vector <string> matrix = {"1,2,3", "4,5,6", "7,8,9"};

How to remove the comma ',' from each string element above in c while keeping the time complexity to be O(n) or using a single loop?

Right now, matrix[0][1] = ',' ;

I want it to be matrix[0][1] = 2;

CodePudding user response:

C 11 solution:

for (auto& s : matrix) s.erase(std::remove(s.begin(), s.end(), ','), s.end());

C 20 solution:

for (auto& s : matrix) std::erase(s, ',');

CodePudding user response:

As you are learning, and don't want you use c STL function, you can write a class that take a string and convert into set of element.

#include <iostream>
#include <vector>
#include <sstream>

struct Matrix {
    int a = 0;
    int b = 0;
    int c = 0;
};

std::istream& operator>>(std::istream& is, Matrix& elem) 
{
    int x = 0;
    int y = 0;
    int z = 0;

    char ch;

    Matrix temp;

    is >> x >> ch >> y >> ch >> z;

    if (is.eof()) {
        temp.a = x;
        temp.b = y;
        temp.c = z;
    } 
    else {
        return is;
    }

    elem = temp;
    return is;
}

std::ostream& operator<<(std::ostream& os, Matrix elem) 
{
    os << elem.a << " " << elem.b << " " << elem.c;

    return os;
}

int main()
{
    std::vector<std::string> matrix = {"1,2,3", "4,5,6", "7,8,9"};

    Matrix el;
    for (std::string s : matrix) {
        std::stringstream iss {s};

        iss >> el;

        std::cout << el << '\n';
    }
  • Related