2017-10-20 50 views
-1

我用C++編寫了一些代碼來在字符串中顯示重複的字符,但是如果一個字符重複三次以上,代碼會不止一次地打印重複的字符。在字符串中顯示重複的字符

例如,如果字符串是aaaddbss,它應該只打印出ads但它打印aaads代替。

我在做什麼錯?

cout << " Please enter a string" << endl; 

cin.getline(input, 100); // example input (ahmad wahidy) the output reads a a h a d instead of a h d 

for (int i = 0;input[i]!='\0'; i++) 
{ 
    for (int j = i+1;input[j]!='\0'; j++) 
    { 
     if (input[i] == input[j]) 
     { 
      cout << input[i] << " "; 
     } 
    } 

} 
cout << endl; 
+1

推測這是C++?這是缺少'input'之類的定義。請做一個完整的例子。我有一種感覺'input'不是'std :: string',它應該是因爲使用原始字符緩衝區是一個糟糕的計劃。 – tadman

+1

我建議你花一些時間閱讀Eric Lippert的[如何調試小程序](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/),並學習如何使用調試器逐行逐行掃描代碼。那麼這個問題會非常明顯。 –

+0

@tadman'input'不能是'std :: string',因爲如果是的話它就不會編譯。 'cin'沒有接受'std :: string'的'getline'方法的重載。 –

回答

3

而不是使用自己的自定義方法,爲什麼不使用簡短和標準的方法?

給定一個std::string input與文本,這將打印出唯一的字符:

std::set<char> unique(input.begin(), input.end()); 
for (auto & c : unique) 
{ 
    std::cout << c << " "; 
} 
std::cout << std::endl; 
1

您可以使用std::countstd::set

#include <string> 
#include <set> 
#include <iostream> 
using namespace std; 

int main() 
{ 
    string s = "hellohowareyou"; 
    set<char>the_set(s.begin(), s.end()); 
    for (char i:the_set) 
     if (count(s.begin(), s.end(), i) > 1) 
      cout << i << endl; 


} 

輸出:

e 
h 
l 
o 
0

如果您不允許使用map (也可能不允許使用set),您可以簡單地使用一個整數數組來計算出現次數,每個可能的char值都有一個條目。請注意,一個字符 - 當作爲ASCII值時 - 可以直接用作數組的索引;但是,爲避免負指數,應首先將每個字符值轉換爲無符號值。

#include <iostream> 
#include <limits> 

int main() { 

    const char* input = "aaaddbss"; 
    int occurrences[UCHAR_MAX+1] = { 0 }; 
    for (int i = 0;input[i] !='\0'; i++) 
    { 
     unsigned char c = input[i]; 
     if (occurrences[c]==0) { 
      occurrences[c]++; 
     } 
     else if (occurrences[c]==1) { 
      occurrences[c]++; 
      cout << "duplicate: " << c << endl; 
     } 
    }cout << endl; 
}