0
点赞
收藏
分享

微信扫一扫

输入字符串,统计单词个数

A邱凌 2022-02-12 阅读 95
c++

结合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;
}

代码部分转自C++统计输入字符串中的单词数量_li123_123_的博客-CSDN博客_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函数

查找在字符串中第一个与指定字符串中的某个字符匹配的字符,返回它的位置。

4.push_back()函数的用法

函数将一个新的元素加到C++统计输入字符串中的单词数量_li123_123_的博客-CSDN博客_c++统计单词数的最后面,位置为当前最后一个元素的下一个元素

5.for(auto i : v)

v是一个可遍历的容器或流,比如vector类型,i就用来在遍历过程中获得容器里的每一个元素。

举报

相关推荐

0 条评论