use getline and while loop to split a string

后端 未结 2 637
醉话见心
醉话见心 2020-12-08 12:18

for example i have a string:

string s = \"apple | orange | kiwi\";

and i searched and there is a way:

stringstream stream(s         


        
2条回答
  •  一生所求
    2020-12-08 12:59

    As Benjamin points out, you answered this question yourself in its title.

    #include 
    #include 
    #include 
    
    int main() {
       // inputs
       std::string str("abc:def");
       char split_char = ':';
    
       // work
       std::istringstream split(str);
       std::vector tokens;
       for (std::string each; std::getline(split, each, split_char); tokens.push_back(each));
    
       // now use `tokens`
    }
    

    Note that your tokens will still have the trailing/leading characters. You may want to strip them off.

提交回复
热议问题