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 −

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.


 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]);
int main(){
   duplicate_char dupchar ;
   char str[] = "tutorialspoint";
   cout<<"The duplicate characters in the string\n";
   return 0;


The duplicate characters in the string character count

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