C Program To Find Duplicate characters in a string
Find Duplicate characters in a string
Today in this article we will discuss how to Find Duplicate characters in a string and we will be using C programming language. We will also disscuss various methods to do the porblem .
Algorithm
- Define a string and take the string as input form the user.
- Two loops will be used to find the duplicate characters. Outer loop will be used to select a character and then initialize variable count by 1 its inside the outer loop so that the count is updated to 1 for every new character.
- Inner loop will compare the selected character with the rest of the characters present in the string.
- If a match is found, it increases the count by 1 and set the duplicates of selected characters by ‘0’ to mark them as visited.
- After the inner loop, if the count of characters is greater than 1, then it has duplicates in the string.
C Code :-
Run
#include <stdio.h>
#include <string.h>
int main()
{
char string[100];
int count;
printf("Enter the string : \n");
scanf("%[^\n]*c",string);
printf("Duplicate characters in a given string: \n");
//Counts each character present in the string
for(int i = 0; i < strlen(string); i++) {
count = 1; //Updates thecount again to 1 for every new character
for(int j = i+1; j < strlen(string); j++) {
if(string[i] == string[j] && string[i] != ' ') {
count++;
//Set string[j] to 0 to avoid printing visited character
string[j] = '0';
}
}
//A character is considered as duplicate if count is greater than 1
if(count > 1 && string[i] != '0')
printf("%c\n", string[i]);
}
return 0;
}
Output:-
Enter the string : prakriti vedi Duplicate characters in a given string: r i
Enter the string : ritika singh Duplicate characters in a given string: i
Enter the string : Aishwariya prasad Duplicate characters in a given string: i s a r

Login/Signup to comment