Remove Duplicate Characters from a String in C

programming

Summary: In this programming example, we will learn to remove all duplicate characters from the string in C.

Input  : "Pencil Programmer"
Output : "Pencil rogam"

To remove all duplicates characters, we have to check for each character whether it occurs more than once in the given string, If so, we remove all its occurrences except the first one.

For example, the word ‘popeye‘ contains multiple p and e, as a result, we keep the first occurrence of each of them and remove their duplicates correspondent.

The string after the elimination of duplicates would become ‘poey‘.

In programming, to eliminate a duplicate character we move all the characters to the left on the right.

#include <stdio.h>
#include <string.h>
 
int main()
{
  int i, j, k;

  //Input string
  char str[30]= "Pencil Programmer";
  
  //find the length of the string
  int length= strlen(str);

  //Iterate through all the characters
  for(i=0; i<length; i++){
      
    //select a character
    char ch = str[i];

    //Check if current character matches any other character in the subsequence
    for(j=i+1; j<length; ){
      
      if(str[i] == str[j]){
        //If yes, then shift the right characters to the left
        for(k=j; k<length; k++){
          str[k] = str[k+1];
        }
        length--;
        
      } else {
          //only increment if the duplicate is not found
          //because after the shift, index j can again have duplicate
          j++;
      }
    } 
  }

  //output the final string
  printf("%s",str);

  return 0;
}

Output:

Pencil rogam

In our program we first find the duplicate character then we delete it by transferring all subsequent characters to one step left.

In this tutorial, we learned how to remove the duplicate characters from the given string in the C programming language.

4 thoughts on “Remove Duplicate Characters from a String in C”

Leave a Reply

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