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

后端 未结 20 2136
时光说笑
时光说笑 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:15

    strtok allows you to pass in multiple chars as delimiters. I bet if you passed in ">=" your example string would be split correctly (even though the > and = are counted as individual delimiters).

    EDIT if you don't want to use c_str() to convert from string to char*, you can use substr and find_first_of to tokenize.

    string token, mystring("scott>=tiger");
    while(token != mystring){
      token = mystring.substr(0,mystring.find_first_of(">="));
      mystring = mystring.substr(mystring.find_first_of(">=") + 1);
      printf("%s ",token.c_str());
    }
    
    0 讨论(0)
  • 2020-11-22 00:16

    This code splits lines from text, and add everyone into a vector.

    vector<string> split(char *phrase, string delimiter){
        vector<string> list;
        string s = string(phrase);
        size_t pos = 0;
        string token;
        while ((pos = s.find(delimiter)) != string::npos) {
            token = s.substr(0, pos);
            list.push_back(token);
            s.erase(0, pos + delimiter.length());
        }
        list.push_back(s);
        return list;
    }
    

    Called by:

    vector<string> listFilesMax = split(buffer, "\n");
    
    0 讨论(0)
提交回复
热议问题