结合C++中的 size_t find_first_not_of (const char* s, size_t pos, size_t n) const;
方法和 size_t find_first_of (const char* s, size_t pos, size_t n) const;
来统计字符串中单词的个数。
#include <iostream>
#include <vector>
#include <string>
// 计算一个字符串中有多少个单词,并保存到一个vector中
using namespace std;
int main(void)
{
string text;
int counts=0;
vector<string> words;
cout<<"Enter the string, end of by:*"<<endl;
getline(cin,text,'*');
const string seqarators {", ;:.\"!?'\n'"}; //单词间的分界符
size_t start{text.find_first_not_of(seqarators)}; //初始化为第一个单词的开头
size_t end{};
while(start != string::npos){
end = text.find_first_of(seqarators, start + 1); // 找到单词的结尾索引
if(end == string::npos){ // 如果到结尾都没有找到分界符,设置end为last-1
end = text.length();
}
words.push_back(text.substr(start, end - start));
counts++;
start = text.find_first_not_of(seqarators, end + 1);
}
for(auto& word:words){
cout<<word<<endl;
}
cout<<"count is:"<<counts<<endl;
return 0;
}