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

后端 未结 20 2112
时光说笑
时光说笑 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-21 23:58

    This is a complete method that splits the string on any delimiter and returns a vector of the chopped up strings.

    It is an adaptation from the answer from ryanbwork. However, his check for: if(token != mystring) gives wrong results if you have repeating elements in your string. This is my solution to that problem.

    vector Split(string mystring, string delimiter)
    {
        vector subStringList;
        string token;
        while (true)
        {
            size_t findfirst = mystring.find_first_of(delimiter);
            if (findfirst == string::npos) //find_first_of returns npos if it couldn't find the delimiter anymore
            {
                subStringList.push_back(mystring); //push back the final piece of mystring
                return subStringList;
            }
            token = mystring.substr(0, mystring.find_first_of(delimiter));
            mystring = mystring.substr(mystring.find_first_of(delimiter) + 1);
            subStringList.push_back(token);
        }
        return subStringList;
    }
    

提交回复
热议问题