Parse (split) a string in C++ using string delimiter (standard C++)

后端 未结 20 2113
时光说笑
时光说笑 2020-11-21 23:44

I am parsing a string in C++ using the following:

using namespace std;

string parsed,input=\"text to be parsed\";
stringstream input_stringstream(input);

i         


        
20条回答
  •  无人共我
    2020-11-22 00:08

    This should work perfectly for string (or single character) delimiters. Don't forget to include #include .

    std::string input = "Alfa=,+Bravo=,+Charlie=,+Delta";
    std::string delimiter = "=,+"; 
    std::istringstream ss(input);
    std::string token;
    std::string::iterator it;
    
    while(std::getline(ss, token, *(it = delimiter.begin()))) {
        while(*(++it)) ss.get();
        std::cout << token << " " << '\n';
    }
    

    The first while loop extracts a token using the first character of the string delimiter. The second while loop skips the rest of the delimiter and stops at the beginning of the next token.

提交回复
热议问题