计算字符串中重复单词的数量 [英] to count number of repeated words in a string
问题描述
我需要编写一个程序,该程序从用户处获取一个字符串,并以重复出现的次数出现在字符串中打印重复出现的单词
例如,我有字符串woo coo woo poo noo chho
那么它应该首先分割字符串,然后打印重复的单词
以及打印该单词的次数.
Hi,
I need to write a program that take a string from user and print the repeated words in a string with the number of ocurence of repeated words
eg I have the string woo coo woo poo noo chho
then it should first split the string and then print the repeated words
and the number of times that word is printed
推荐答案
您尚未指定到目前为止尝试过的内容.因此,我不知道这是否是您问题的确切答案,但这是我的提示:您可以使用标准的 ^ ]容器,以便简化很多事情.
这是一个简单的示例:
You didn''t specify what you''ve tried so far. So I don''t know if this is an exact answer to your question but here is my hint for you: you can use the standard std::map[^] container in order to simplify things a lot.
Here is a quick example for you:
#include <iostream>
#include <sstream>
#include <string>
#include <map>
int main()
{
// The test string
std::string str("woo coo woo poo noo chho");
// Count the number of occurrences for each word
std::string word;
std::istringstream iss(str);
std::map<std::string, std::size_t> occurrences;
while (iss >> word) ++occurrences[word];
// Print the results
for (std::map<std::string, std::size_t>::iterator it = occurrences.begin();
it != occurrences.end(); ++it)
{
std::cout << "Word: " << it->first << "\t Occurrences: " << it->second << std::endl;
}
std::cin.get();
return 0;
}
// ==== The program output is: ====
// Word: chho Occurrences: 1
// Word: coo Occurrences: 1
// Word: noo Occurrences: 1
// Word: poo Occurrences: 1
// Word: woo Occurrences: 2
该程序只是一个演示,但可能对您有用.
如果您有任何问题,请更新您的原始问题和/或发表评论,但是这次请具体说明您的问题. :)
This program is only a demo but it might be useful for you.
If you have some problems please update your original question and/or post a comment but this time please be specific about your problem. :)
此 [^ ]讨论可能会对您有所帮助.
This[^] discussion might help you.
这篇关于计算字符串中重复单词的数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!