JMLdev JMLdev - 1 month ago 5x
C++ Question

Parse integers in string in C++

I have a string that looks like this:


and I want to convert it to an array (or vector) of strings:

["{", "{", "2", "}", ",", "{", "10", ",", "1", "}", ",", "9", "}"]

I can't just pull out each character separately because some of the integers may be double-digit, and I can't figure out how to use stringstream because there are multiple delimiters on the integers (could be followed by , or })


The logic is straightforward:

  1. Iterate over the string.

  2. push_back() each character as a string of its own into the output vector, unless it's a digit and the last character was a digit, in which case append the digit to the last string in the output vector:

That's it.

std::string s="{{2,3},{10,1},9}";

std::vector<std::string> v;

bool last_character_was_a_digit=false;

for (auto c:s)
    if ( c >= '0' && c <= '9')
        if (last_character_was_a_digit)
    v.push_back(std::string(&c, 1));