定义分隔符
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*
输出