开始。在这种情况下,你可以利用关联容器。 C++有多种选择。例如,您可以使用std::map
。在下面的代码中,您可以计算文本中出现多少个单词。
#include <iostream>
#include <string>
#include <map>
#include <algorithm>
int main()
{
std::map<std::string,int> strCount;
std::string str("AA BB ABC AA GE AAf FF JJ BB CC ");
std::string temp;
// Split String Based on Whitespace (i.e. you need to modify it to suit the text format you have.)
for (int i(0); i < str.size(); ++i){
temp += str[i];
if (str[i] == ' '){
temp.pop_back();
++strCount[temp]; // <-- if element new, insert it in map and associate new counter, otherwise increment counter of element.
temp.clear();
}
}
std::map<std::string,int>::const_iterator iter;
for(iter = strCount.begin(); iter != strCount.end(); iter++) {
std::cout << "#: " << iter->second << " string: " << iter->first << std::endl;
}
return 0;
}
上述代码的输出是
#: 2 string: AA
#: 1 string: AAf
#: 1 string: ABC
#: 2 string: BB
#: 1 string: CC
#: 1 string: FF
#: 1 string: GE
#: 1 string: JJ
的_best_解决方案是任何适合您的需求最多。你需要它快速,还是易于阅读/维护?你可以随时编写所有三个,在它们上运行基准测试,并查看你想使用哪一个。 –
@FrançoisAndrieux我加了一点点说明。 –
如果你想在字符串中找到相似的单词,我认为你必须将每个单词存储在向量中并对其进行排序。在这种情况下,相似的单词将在序列中逐一定位。在这里你得到下一个复杂度O(NlogN)+ O(N)(排序+检查向量中的每个元素)。 – arturx64