Print all the duplicates in the input string in C++

C++Server Side ProgrammingProgramming

In this problem, we are given a string and we have to find all the characters that are duplicated along with their number of occurrences in the string.

Let’s take an example to understand the problem −

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

Explanation− The frequencies of occurrence of each character are t → 3; u → 1; o → 2; r → 1; i → 2; a → 1; s → 1; n → 1.

Now, to solve this problem we will find the character count and store it in an array from the string. And then print the characters and occurrences where freq. It is more than 1.

Example

 Live Demo

# 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;
}

Output

The duplicate characters in the string character count

i 2
o 2
t 3
raja
Published on 17-Jan-2020 14:35:08
Advertisements