Because C + + string does not have the split function, so the string division of words must be written by themselves, it is equivalent to implement a split function it!
If you need to split the word according to a single character, it is good to read it directly with Getline, very simple
1#include <iostream>2#include <vector>3#include <string>4#include <sstream>5 using namespacestd;6 7 intMain ()8 {9 stringwords;Tenvector<string>results; OneGetline (cin, words);
A Istringstream SS (words); - while(!ss.eof ()) - { the stringWord; -Getline (SS, Word,','); - Results.push_back (word); - } + for(auto Item:results) - { +cout << Item <<" "; A } at}
If it is a multi-character segmentation, for example,.! And so on, you need to write a function similar to split:
1#include <iostream>2#include <vector>3#include <string>4#include <sstream>5 using namespacestd;6 7vector<Char> is_any_of (stringstr)8 {9vector<Char>Res;Ten for(auto S:str) One Res.push_back (s); A returnRes; - } - the voidSplit (vector<string>& result,stringSTR, vector<Char>delimiters) - { - result.clear (); -Auto start =0; + while(Start <str.size ()) - { + //split based on multiple separators AAuto Itres = Str.find (delimiters[0], start); at for(inti =1; I < delimiters.size (); ++i) - { -Auto it =Str.find (delimiters[i],start); - if(It <itres) -Itres =it; - } in if(Itres = =string:: NPOs) - { toResult.push_back (Str.substr (Start, str.size ()-start)); + Break; - } theResult.push_back (Str.substr (Start, Itres-start)); *Start =itres; $++start;Panax Notoginseng } - } the + intMain () A { the stringwords; +vector<string>result; - getline (CIN, words); $Split (result, words, is_any_of (", .?!")); $ for(auto Item:result) - { -cout << Item <<' '; the } -}
For example: Enter Hello world! Welcome to my Blog,thank you!
C + + split string (similar to Boost::split)