原创内容,转载请注明原文网址:http://homeqin.cn/a/wenzhangboke/jishutiandi/youxikaifa/2018/1222/256.html
常州微信公众平台开发:c++分割字符串(类似于boost::split)
由于c++字符串没有split函数,所以字符串分割单词的时候必须自己手写,也相当于自己实现一个split函数吧!
如果需要根据单一字符分割单词,直接用getline读取就好了,我们这常州游戏开发运营很简单
1 #include
2 #include
3 #include <</span>string>
4 #include
5 using namespace std;
6
7 int main()
8 {
9 string words;
10 vector<</span>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
2 #include
3 #include <</span>string>
4 #include
5 using namespace std;
6
7 vector<</span>char> is_any_of(string str)
8 {
9 vector<</span>char> res;
10 for (auto s : str)
11 res.push_back(s);
12 return res;
13 }
14
15 void split(vector<</span>string>& result, string str, vector<</span>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<</span>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!
常州游戏开发培训提供的另一种实现方法,使用strtok_s分割字符串:
1 std::vectorstring> split(const std::string& str, const std::string& delimiter)
2 {
3 char* save = nullptr;
4 char* token = strtok_s(const_cast<</span>char*>(str.c_str()), delimiter.c_str(), &save);
5 std::vectorstring> 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 }
上篇:上一篇:常州网站开发mysql问题:encountered during command exec
下篇:下一篇:常州手游开发-简单虚拟摇杆控制移动