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];
      } else {
          //only increment if the duplicate is not found
          //because after the shift, index j can again have duplicate

  //output the final string

  return 0;


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.

This Post Has 4 Comments

  1. Supun

    The program fails when we enter “cecc”. Can you please give a solution for that?

    1. Adarsh Kumar

      Thanks, Supun for pointing it out. I have updated the code.

  2. nobody

    ur code does not work.

    1. Adarsh Kumar

      Please check again.

Leave a Reply