简体   繁体   中英

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

ab~cd

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++?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM