2017-05-03 162 views
0

程序使用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

你總是可以使用['標準:: count_if'(HTTP:// en.cppreference.com/w/cpp/algorithm/count),[像這樣](http://coliru.stacked-crooked.com/a/17f3f53996e803f8)。 – cdhowie

+0

如果你定義了「重複」,這樣'main'的一個外觀根本不算重複,那麼邏輯上,'apple'只重複一次(第一次出現不是重複)。 – ShadowRanger

+0

你只是排序前4個字符串,不是全部6個字符串。 –

回答

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 

Live Demo

相關問題