Example:
Input string: Programming in C!
Output after removing duplicate: Progamin C!
Required knowledge
Basic C programming, Loop, String, FunctionsLogic to remove repeated characters from string
Removing all repeated characters from a given string involves basic three tasks:- Run a loop from starting to end character in given string.
- Find all occurrences of current character in the string.
- 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!
String before removing duplicates: Programming in C!
String after removing duplicates: Progamin C!
Happy coding ;)
You may also like
- String programming exercises index.
- C program to reverse a string.
- C program to check palindrome string.
- C program to count occurrences of a character in a string.
- C program to find highest frequency character in a string.
- C program to find lowest frequency character in a string.
- C program to count frequency of each characters in a string.
- C program to search all occurrences of a word in a string.
- C program to count occurrences of a word in a string.
- C program to remove all occurrences of a word in a string.