Not much to say, directly on the code
If you need to split the word according to a single character, read it directly with Getline, very simple
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
using namespace std;
int main ()
{
string words;
vector<string> results;
Getline (cin, words);
Istringstream SS (words);
while (!ss.eof ())
{
string word;
Getline (SS, Word, ', ');
Results.push_back (word);
for (auto Item:results)
{
cout << item << "";
}
}
If it is a variety of character segmentation, for example,.! And so on, you need to write a function similar to split:
#include <iostream> #include <vector> #include <string> #include <sstream> using namespace s
td
vector<char> is_any_of (String str) {vector<char> res;
for (auto S:str) res.push_back (s);
return res;
} void Split (vector<string>& result, string str, vector<char> delimiters) {result.clear ();
Auto start = 0;
while (Start < Str.size ()) {//split auto Itres = Str.find (Delimiters[0], start) according to multiple delimiters;
for (int i = 1; i < delimiters.size (); ++i) {Auto it = Str.find (Delimiters[i],start);
if (it < itres) Itres = it;
} if (itres = = String::npos) {result.push_back (Str.substr (Start, str.size ()-start);
Break
} result.push_back (Str.substr (Start, Itres-start));
start = Itres;
++start;
int main () {string words;
vector<string> result;
Getline (cin, words); Split (result, words, is_any_of (",.?!"));
for (auto Item:result) {cout << item << '; }
}
For example: Enter Hello world! Welcome to my Blog,thank you!
The above is C + + how to split string sample code of the entire content, we have learned? I hope this article is helpful to you when you use C + +.