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

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

    A very simple/naive approach:

    vector words_seperate(string s){
        vector ans;
        string w="";
        for(auto i:s){
            if(i==' '){
               ans.push_back(w);
               w="";
            }
            else{
               w+=i;
            }
        }
        ans.push_back(w);
        return ans;
    }
    

    Or you can use boost library split function:

    vector result; 
    boost::split(result, input, boost::is_any_of("\t"));
    

    Or You can try TOKEN or strtok:

    char str[] = "DELIMIT-ME-C++"; 
    char *token = strtok(str, "-"); 
    while (token) 
    { 
        cout<

    Or You can do this:

    char split_with=' ';
    vector words;
    string token; 
    stringstream ss(our_string);
    while(getline(ss , token , split_with)) words.push_back(token);
    

提交回复
热议问题