C program to remove all repeated characters in a string

Write a C program to remove all repeated characters in a string using loops. How to remove all duplicate characters from a string using for loop in C programming. Program to find and remove all duplicate characters in a string. Logic to remove all repeated character from string in C program.

Example

Input

Input string: Programming in C.

Output

String after removing duplicate characters: Progamin C.

Required knowledge

Basic C programming, Loop, String, Functions

Must know -

Logic to remove repeated characters from string

Below is the step by step descriptive logic to remove repeated characters from string.

  1. Input string from user, store it in some variable say str.
  2. Run a loop from start to end character of the given string str.
  3. For each character ch in the string, remove all next occurrences of ch.

Program to remove all repeated characters in string

/**
 * C program to remove all repeated characters from a given string
 */
#include <stdio.h>
#define MAX_SIZE 100 // Maximum string size

/* Function declarations */
void removeDuplicates(char * str);
void removeAll(char * str, const char toRemove, int index);


int main()
{
    char str[MAX_SIZE];

    /* Input string from user */
    printf("Enter any string: ");
    gets(str);

    printf("String before removing duplicates: %s\n", str);

    removeDuplicates(str);

    printf("String after removing duplicates: %s\n", str);

    return 0;
}


/**
 * Remove all duplicate characters from the given string
 */
void removeDuplicates(char * str)
{
    int i = 0;

    while(str[i] != '\0')
    {
        /* Remove all duplicate of character string[i] */
        removeAll(str, str[i], i + 1);
        i++;
    }
}

/**
 * Remove all occurrences of a given character from string.
 */
void removeAll(char * str, const char toRemove, int index)
{
    int i;

    while(str[index] != '\0')
    {
        /* If duplicate character is found */
        if(str[index] == toRemove)
        {
            /* Shift all characters from current position to one place left */
            i = index;
            while(str[i] != '\0')
            {
                str[i] = str[i + 1];
                i++;
            }
        }

        index++;
    }
}

Output

Enter any string: Programming in C.
String before removing duplicates: Programming in C.
String after removing duplicates: Progamin C.

Happy coding 😉

Write your doubts or suggestion. I will try my best to help. You must escape source code before commenting. To format your source code paste your source code inside
<pre><code> ----Your Source Code---- </code></pre>