Gaurav Hira
Gaurav Hira

Reputation: 3

split a string using multiple delimiters (including delimiters) in c++

I have a string which I input as follows

using namespace std;

string s;
getline(cin, s);

I input

a.b~c.d

I want to split the string at . and ~ but also want to store the delimiters. The split elements will be stored in a vector.

Final output should look like this

a
.
b
~
c
.
d

I saw a solution here but it was in java.

How do I achieve this in c++?

Upvotes: 0

Views: 779

Answers (1)

cigien
cigien

Reputation: 60440

This solution is copied verbatim from this answer except for the commented lines:

std::stringstream stringStream(inputString);
std::string line;
while(std::getline(stringStream, line)) 
{
    std::size_t prev = 0, pos;
    while ((pos = line.find_first_of(".~", prev)) != std::string::npos)  // only look for . and ~
    {
        if (pos > prev)
            wordVector.push_back(line.substr(prev, pos-prev));
        wordVector.push_back(line.substr(pos, 1));               // add delimiter 
        prev = pos+1;
    }
    if (prev < line.length())
        wordVector.push_back(line.substr(prev, std::string::npos));
}

I haven't tested the code, but the basic idea is you want to store the delimiter character in the result as well.

Upvotes: 2

Related Questions