C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

Strings in C

Remove duplicate characters

C Program: Remove Duplicate Characters from a String

C

#include <stdio.h>

#include <string.h>

 

int main() {

    char str[200], result[200];

    int i, j, k = 0;

    int len;

    int found;

 

    // Input string

    printf("Enter a string: ");

    fgets(str, sizeof(str), stdin);

 

    len = strlen(str);

 

    // Remove newline character (if present)

    if (str[len - 1] == '\n')

        str[len - 1] = '\0';

 

    // Traverse each character

    for (i = 0; str[i] != '\0'; i++) {

        found = 0;

 

        // Check if character already exists in result

        for (j = 0; j < k; j++) {

            if (str[i] == result[j]) {

                found = 1;

                break;

            }

        }

 

        // If not found, add it to result

        if (!found) {

            result[k++] = str[i];

        }

    }

 

    result[k] = '\0'; // Null terminate the result string

 

    printf("String after removing duplicate characters: %s\n", result);

 

    return 0;

}

Output

 
OUTPUT :
Enter a string: programming
String after removing duplicate characters: progamin

Explanation

  • The program uses two arrays:
    • str → original string
    • result → stores unique characters only
  • For each character in str, the program checks if it already exists in result.
    • If not, it appends it.
    • If yes, it skips that character.
  • Works for all characters (including spaces and digits).