文本字符串提取单词

定义分隔符

string separators{" ,;:.\"!?'\n"};

分别是

空格,逗号,分号,冒号,句号,双引号,感叹号,问好,单引号,换行符

因为

文本串里除了分隔符就是字母

所以

找到第一个不是分隔符的位置 相当于 找到单词开头字母的位置

然后

再从此字母位置后面找到第一个分隔符的位置

这样

前面一位就是此单词最后一个字母的位置

如果以0为坐标描述第一个位置,那么1就是第二个位置,以此类推

设start为第一个不是分隔符的位置坐标,end为start后面第一个分隔符的位置坐标

那么单词的长度就是

end - start

举例

有以下文本串

,fuck.

第一个不是分隔符的字符是第二个字符f

坐标是1

往后

第一个分隔符是第六字符.

坐标是5

那么单词长度就是

5 - 1 = 4

C++代码

#include<iostream>
#include<iomanip>
#include<vector>
#include<string>
using namespace std;

int main() {
	string text;
	cout << "Enter some text terminated by *:\n";
	getline(cin, text, '*');

	const string separators{ " ,;:.\"!?'\n" };
	vector<string> words;
	vector<int> counts;

	string word;
	size_t start{ text.find_first_not_of(separators) };
	size_t end{};
	size_t max_size{};
	bool is_in{ false };
	while (start != string::npos) {
		end = text.find_first_of(separators, start + 1);
		if (end == string::npos)
			end = text.length();

		word = text.substr(start, end - start);
		is_in = false;
		for (size_t i{}; i < words.size(); ++i) {
			if (words[i] == word) {
				is_in = true;
				++counts[i];
				break;
			}
		}

		if (!is_in) {
			if (max_size < word.length()) max_size = word.length();
			words.push_back(word);
			counts.push_back(1);
		}
		start = text.find_first_not_of(separators, end + 1);
	}

	cout << "Your string contains the following " << words.size() << " words and counts\n";
	size_t count{};
	size_t perline{ 3 };
	for (size_t i{}; i < words.size(); ++i) {
		cout << setw(max_size) << left << words[i] 
			 << setw(4) << right << counts[i] << " ";
		if (++count % perline == 0) cout << endl;
	}

	return 0;
}

输入

QUOTES ON FAITHFaith is the bird that feels the light when the dawn is still
dark.Rabindranath Tagore Oh,the comfort,the inexpressible comfort of feeling 
safe with a person*

输出

在这里插入图片描述

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值