在 C++ 中列印輸入字串中的所有重複項


在此問題中,給定一個字串,我們必須找到字串中所有重複的字元及其在字串中的出現次數。

我們舉一個例子來理解這個問題:

Input:
TutorialsPoint
Output:
t (3)
o (2)
i (2)

說明- 每個字元的出現頻率為:t → 3; u → 1; o → 2; r → 1; i → 2; a → 1; s → 1; n → 1。

現在,為了解決這個問題,我們將找出字元數,並將其從字串中儲存在一個數組中。然後列印 freq 處字元和出現次數。它大於 1。

示例

 即時演示

# include <iostream>
using namespace std;
# define NO_OF_CHARS 256
class duplicate_char{
   public :
   void charCounter(char *str, int *count){
      int i;
      for (i = 0; *(str + i); i++)
      count[*(str + i)]++;
   }
   void printDuplicateCharacters(char *str){
      int *count = (int *)calloc(NO_OF_CHARS, sizeof(int));
      charCounter(str, count);
      int i;
      for (i = 0; i < NO_OF_CHARS; i++)
         if(count[i] > 1)
            printf("%c\t\t %d \n", i, count[i]);
      free(count);
   }
};
int main(){
   duplicate_char dupchar ;
   char str[] = "tutorialspoint";
   cout<<"The duplicate characters in the string\n";
   cout<<"character\tcount\n";
   dupchar.printDuplicateCharacters(str);
   return 0;
}

輸出

字串字元數中的重複字元

i 2
o 2
t 3

更新時間:17-Jan-2020

378 檢視次數

啟動您的 職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.