Remove all repeated characters from a given string with C.
#include <stdio.h>
/* Function declarations */
void removeDuplicates(char *str);
void removeAll(char *str, const char toRemove, int index);
int main()
{
char str[100];
/* 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++;
}
}
else
{
index++;
}
}
}
Output
Enter any string : Learn With Reza
String before removing duplicates : Learn With Reza
String after removing duplicates : Learn WithRz
0 Comments