String Exercises
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.
Required knowledge
Basic C programming, C if-else, C for loop, Array, functions, Strings
Logic to remove repeated characters from string
Below is the step by step descriptive logic to remove repeated characters from string.
- Input string from user, store it in some variable say str.
- Run a loop from start to end character of the given string str.
- 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++; } }