程序使用qsort对单词进行排序。
这是我到目前为止的代码,我如何计算重复的单词?例如,苹果重复两次,而主要根本不重复。
int main()
{
//6 entries with 20 max
char strings[6][20] = { "apple", "apple", "strawberries", "bananas", "dairy", "main" };
qsort(strings, 4, 20, (int(*)(const void*, const void*))strcmp);
// display the strings in ascending lexicographic order
for (int i = 0; i < 6; i++) {
cout << strings[i] << "\n";
}
return 0;
}
答案 0 :(得分:0)
尝试更像这样的事情:
#include <iostream>
#include <algorithm>
#include <string>
static const int max_strings = 6;
int main()
{
//6 entries
std::string strings[max_strings] = { "apple", "apple", "strawberries", "bananas", "dairy", "main" };
// sort the strings in ascending order
std::sort(strings, &strings[max_strings]);
// display the strings and their repeat counts
int i = 0;
while (i < max_strings)
{
std::string str = strings[i];
int count = 1;
while (++i < max_strings)
{
if (strings[i] != str)
break;
++count;
}
std::cout << "'" << str << "' appears " << count << " time";
if (count != 1)
std::cout << "s";
std::cout << std::endl;
}
return 0;
}
输出:
'apple' appears 2 times 'bananas' appears 1 time 'dairy' appears 1 time 'main' appears 1 time 'strawberries' appears 1 time