c++如何分割字符串示例代码

话不多说,直接上代码

如果需要根据单一字符分割单词,直接用getline读取就好了,很简单

 #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 << " ";
   }
 }

如果是多种字符分割,比如,。!等等,就需要自己写一个类似于split的函数了:

 #include <iostream>
 #include <vector>
 #include <string>
 #include <sstream>
 using namespace std;
 
 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())
   {
     //根据多个分割符分割
     auto itRes = str.find(delimiters[0], start);
     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 << ' ';
   }
 }

例如:输入hello world!Welcome to my blog,thank you!

以上就是c++如何分割字符串示例代码的全部内容,大家学会了吗?希望本文对大家使用C++的时候有所帮助。