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()
{
  //Input string
  char str[30]= "Pencil Programmer";
  
  //find ength of the string
  int length= strlen(str);

  //Iterate through all the characters
  for(int i=0; i<length; i++){

    //select a character
    char ch = str[i];

    //check if the character mathches any other in later part
    for(int j=i+1; j<length; j++){
      if(str[i] == str[j]){
        //If yes, then shift the right characters to the left
        for(int k=j; k<length; k++){
          str[k] = str[k+1];
        }
        length--;
      }
    } 
  }

  //output 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.

Leave a Reply

12 + 1 =