How to print duplicate characters from a given string in C++

In this C++ program, we are going to print duplicate characters from a given string with simple string commands and nested loop. This problem is based on the application of character array (string) which has many applications. Following is a short and descriptive solution to perform this task.

Print duplicate characters from a given string in C++

Problem statement

A user enters a string of any length. Write a C++ program to print duplicate characters from that string.

  • Treat upper and lower cases as different.

Problem approach

  • Declare a string of sufficient length.
  • Take the input for the string from the user.
  • Analyze each letter of the string.
  • Print duplicate values on the screen.

Program/ Source code

Following C++ program is able to detect duplicate characters from a given string, is written and successfully compiled in CodeBlocks v16.01.

/* C++ program to detect duplicate characters in given string**
 ** enter string value of your choice**
 ***enter different string values for different results***
 note: enter the string which has duplicate characters otherwise no values will be printed....
 */

#include <iostream>
#include<string.h>

using namespace std;
int main()
{
    char string[80];
    cout<<"Enter string: ";
    cin.getline(string,80);

    cout<<"Duplicate characters are following"<<endl;
    for(int i=0;i<strlen(string);i++){                     // nested loop statement
        for(int j=i+1;j<strlen(string);j++){
            if(string[i]==string[j]){                   // logic to detect duplicate character
                cout<<string[i]<<endl;                  // duplicate character
                break;
            }
        }
    }

    return 0;
}

Example output

Enter string: sample string for working
Duplicate characters are following
s

r
i
n
g

o
r

Process returned 0 (0x0) execution time : 12.643 s
Press any key to continue.
Enter string: hello world
Duplicate characters are following
l
l
o

Process returned 0 (0x0) execution time : 10.782 s
Press any key to continue.

Program explanation

  • Initialize a string of length 80.
  • Take the input string value from the user.
  • Use nested for loop to traverse through the string.
  • Use a conditional statement (if) to perform the function.
  • Print the duplicate values each time any duplicate character is detected.

Also, read

Find the size of string without using library functions in C++

Find the size of string without using library functions in C++

Leave a Reply

Your email address will not be published. Required fields are marked *