[英]If a word is repeated many times in a string, how can I count the number of repetitions of the word and their positions?
[英]How to count number of times word is repeated in C++
嗨,我在這段代碼上遇到了麻煩。
計算唯一單詞的最佳方法是使用std::unordered_map<std::string, int>
,然后在地圖中遞增值: wordMap[word]++;
請注意,如果這是單詞的第一次出現,則將創建默認值並將其設置為0,非常適合此任務。
除此之外,當存在std :: sort時,對自己進行排序也不是一件好事,這在大多數情況下是非常好的。
氣泡排序:
vector<string> strings = split(str);
for (int i = 0; i < strings.size(); i++) {
for (int j = 0; j < strings.size() - 1; j++) {
if (strings[j + 1] < strings[j]) {
string tmp = strings[j];
strings[j] = strings[j + 1];
strings[j + 1] = tmp;
}
}
}
訂購后計算字數:
string prev = strings[0];
int counter = 1;
for (int i = 1; i < strings.size(); i++) {
if (strings[i] == prev) {
counter++;
} else {
cout << prev << ": " << counter << " ";
prev = strings[i];
counter = 1;
}
}
您可以從algorithm
使用std :: find:
std::find(strings.begin(), strings.end(), the_word_you_looking_for) != strings.end()
這將返回一個布爾值(如果存在則為true,否則為false) 。
您還可以設置一個計數器,然后在遇到每個true
時對其進行遞增。
一種方法是將所有子字符串保留在向量中,然后在向量上使用std :: count函數並將結果放入映射中。 這是示例代碼
std::string s = "This is very good text and is really good to read";
// Putting all substrings into a vector.. Need code to do that, for simplicity I am showing here manually
vector<string> v1;
v1.push_back("This");
v1.push_back("is");
v1.push_back("very");
v1.push_back("good");
v1.push_back("text");
v1.push_back("and");
v1.push_back("is");
v1.push_back("rally");
v1.push_back("good");
v1.push_back("to");
v1.push_back("read");
// Map to create the result
map<string, int> mp;
for (auto v : v1) {
size_t n = std::count(v1.begin(), v1.end(), v);
mp[v] = n;
}
for (auto mvalue : mp) {
cout << "String = " << mvalue.first.c_str() << " Count Is " << mvalue.second << endl;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.