c++分割字符串(类似于boost::split)

  由于c++字符串没有split函数,所以字符串分割单词的时候必须自己手写,也相当于自己实现一个split函数吧!

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

 1 #include <iostream>
 2 #include <vector>
 3 #include <string>
 4 #include <sstream>
 5 using namespace std;
 6 
 7 int main()
 8 {
 9     string words;
10     vector<string> results;
11     getline(cin, words);
12 istringstream ss(words); 13 while (!ss.eof()) 14 { 15 string word; 16 getline(ss, word, ','); 17 results.push_back(word); 18 } 19 for (auto item : results) 20 { 21 cout << item << " "; 22 } 23 }

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

 1 #include <iostream>
 2 #include <vector>
 3 #include <string>
 4 #include <sstream>
 5 using namespace std;
 6 
 7 vector<char> is_any_of(string str)
 8 {
 9     vector<char> res;
10     for (auto s : str)
11         res.push_back(s);
12     return res;
13 }
14 
15 void split(vector<string>& result, string str, vector<char> delimiters)
16 {
17     result.clear();
18     auto start = 0;
19     while (start < str.size())
20     {
21         //根据多个分割符分割
22         auto itRes = str.find(delimiters[0], start);
23         for (int i = 1; i < delimiters.size(); ++i)
24         {
25             auto it = str.find(delimiters[i],start);
26             if (it < itRes)
27                 itRes = it;
28         }
29         if (itRes == string::npos)
30         {
31             result.push_back(str.substr(start, str.size() - start));
32             break;
33         }
34         result.push_back(str.substr(start, itRes - start));
35         start = itRes;
36         ++start;
37     }
38 }
39 
40 int main()
41 {
42     string words;
43     vector<string> result;
44     getline(cin, words);
45     split(result, words, is_any_of(", .?!"));
46     for (auto item : result)
47     {
48         cout << item << ' ';
49     }
50 }

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

  感谢@chxuan提供的另一种实现方法,使用strtok_s分割字符串:

 1 std::vector<std::string> split(const std::string& str, const std::string& delimiter)
 2 {
 3     char* save = nullptr;
 4     char* token = strtok_s(const_cast<char*>(str.c_str()), delimiter.c_str(), &save);
 5     std::vector<std::string> result;
 6     while (token != nullptr)
 7     {
 8         result.emplace_back(token);
 9         token = strtok_s(nullptr, delimiter.c_str(), &save);
10     }
11     return result;
12 }
原文地址:https://www.cnblogs.com/zhangbaochong/p/5755225.html