由于c++字符串没有split函数,所以字符串分割单词的时候必须自己手写,也相当于自己实现一个split函数吧!
如果需要根据单一字符分割单词,直接用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 = ;
while (start < str.size())
{
//根据多个分割符分割
auto itRes = str.find(delimiters[], start);
for (int i = ; 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!
感谢@chxuan提供的另一种实现方法,使用strtok_s分割字符串:
std::vector<std::string> split(const std::string& str, const std::string& delimiter)
{
char* save = nullptr;
char* token = strtok_s(const_cast<char*>(str.c_str()), delimiter.c_str(), &save);
std::vector<std::string> result;
while (token != nullptr)
{
result.emplace_back(token);
token = strtok_s(nullptr, delimiter.c_str(), &save);
}
return result;
}