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.

Example:
Input string: Programming in C!
Output after removing duplicate: Progamin C!

Required knowledge

Basic C programming, Loop, String, Functions

Logic to remove repeated characters from string

Removing all repeated characters from a given string involves basic three tasks:
  1. Run a loop from starting to end character in given string.
  2. Find all occurrences of current character in the string.
  3. Remove all occurrences of current character from the given string except the current character.


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 size of the string


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




int main()
{
    char string[MAX_SIZE];

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

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

    removeDuplicates(string);

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

    return 0;
}




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

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



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

    i = index + 1;

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

        i++;
    }
}


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

Happy coding ;)


Any doubt or suggestion write here. I will try my best to help. Before posting your code you must escape it to view. To format your source code and use format highlighting, post your source code inside
< code >< pre > -- Your source code -- < /pre >< /code > (Remove spaces from pre and code tags).

No comments:

Post a Comment