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

时间:2022-11-04 00:10:39

话不多说,直接上代码

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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#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的函数了:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#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++如何分割字符串示例代码的全部内容,大家学会了吗?希望本文对大家使用C++的时候有所帮助。