使用字符串::find搜索不同的单词.对诸如“;是;
using string::find to search for words that are distinct. Having problems with smaller words like "is."
对于一项作业,我应该输入一段文本,并根据该段文本生成一个不同单词的列表以及它们的出现频率。例如,短语"pie eating pie smile
"具有3 distinct
个单词。
我遇到的主要问题是string::find在单词"comprise
"中看到了诸如"is
"之类的单词,所以单词"is
"是不明显的。
我会使用字符串提取器从文件中读取单词,将它们插入到std::set
中,然后打印出结果中不同的单词:
std::istream in("yourfile.txt");
std::set<std::string> words {std::istream_iterator<std::string>(in),
std::istream_iterator<std::string>()};
std::copy(words.begin(), words.end(),
std::ostream_iterator<std::string>(std::cout, "n"));
要获得出现频率,请切换到std::map<std::string, size_t>
,并在阅读时增加每个单词的条目:
std::map<std::string, size_t> counts;
std::string word;
while (infile >> word)
++counts[word];
照原样,这将使单词按字母顺序排列。如果你不在乎这一点,你可能会(也可能不会)通过使用std::unordered_map
来提高速度。
您的算法应该是这样的:
- 读一行
- 将记号(单词)分开
- 增加每个找到的令牌的计数
- 在1处重复,除非EOF
您应该能够为自己提取和处理每个令牌。
不要试图在未kenized的输入中查找令牌
提示:查看std::unordered_map<string, size_t>
。它允许您高效地查找代币并更新其计数。
相关文章:
- 从字符串变量中逐字符读取单词
- 使用std::mt19937从字符串中返回一个随机单词
- C++-字符串是否包含一个带有简单循环的单词
- 在C++中查找(奇怪的)字符串中的单词
- 当字符串是某个单词时给出输出?
- 替换字符串中的单词,但忽略引号中的单词
- 替换字符串位置 X 中的单词C++
- 视觉C++使用 map 来比较字符串中的每个单词
- 给定一个单词数组和一个字符串,如何计算给定字符串中的所有单词
- 输出返回编号。等于输入字符串的单词的字符串数
- 在字符串的每个单词的末尾插入字符串
- 分析字符串中的双精度和单词
- 如何使用运算符>>在自定义字符串中输入多个单词?
- 反转字符串中单词的位置,而不更改 O(1) 空格限制中特殊字符的顺序
- 使用正则表达式c++从单词和分隔符之间的字符串中提取所有子字符串
- 从文件 (C++) 输入两个单词字符串
- 在一行中输入具有其他输入类型的多个单词字符串
- 打印以 "a" 开头的单词(字符串中)
- 如何让我的代码以不会切断单词(字符串)的方式运行?
- 句子变成单词c++字符串