结合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 separators{ ", ;:.\"!?'\n'" }; //单词间的分界符
size_t start{ text.find_first_not_of(separators) }; //初始化为第一个单词的开头
size_t end{};
while (start != string::npos) {
end = text.find_first_of(separators, 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(separators, end + 1);
}
for (auto& word : words) {
cout << word << endl;
}
cout << "count is:" << counts << endl;
return 0;
}
代码部分转自C++统计输入字符串中的单词数量_li123_123_的博客-优快云博客_c++统计单词数
知识补充
1.c++中substr函数用法
#include<string>
#include<iostream>
using namespace std;
int main()
{
string s("12345asdf");
string a = s.substr(0,5); //获得字符串s中从第0位开始的长度为5的字符串
cout << a << endl;
}
输出结果为12345
2.string:npos
查找字符串a是否包含子串b,不是用strA.find(strB) > 0 而是 strA.find(strB) != string:npos
其中string:npos是个特殊值,说明查找没有匹配。
3.first_find_of函数
查找在字符串中第一个与指定字符串中的某个字符匹配的字符,返回它的位置。
示例
string str = "Mississippi";
int index;
// 's ' 在index 为 2、3、5、6处出现
index = str.find_first_of('s',0); // index为 2
index = str.find_first_of('s',4); // index为 5
index = str.find_first_of('s',7); // index为 -1
4.push_back()函数的用法
函数将一个新的元素加到vector的最后面,位置为当前最后一个元素的下一个元素
5.for(auto i : v)
v是一个可遍历的容器或流,比如vector类型,i就用来在遍历过程中获得容器里的每一个元素。
6.size_t
size_t是全局定义的类型;size_type是STL类中定义的类型属性,用以保存任意string和vector类对象的长度
size_t size = sizeof(i);
// 用sizeof操作得到变量i的大小,这是一个size_t类型的值
// 可以用来对一个size_t类型的变量做初始化