I have piece of code in C which removes any duplicate character in a string .But i am doing it in two loops and would like it to optimize to one loop .
void removeDuplicates(char* ptr)
{
int end = 1;
int length = strlen(ptr);
int current;
int i;
current = 1;
for(end=1; end<length; end++)
{
for(i=0; i<end; i++)
{
if(ptr[end] == ptr[i])
break;
}
if(i == end)
{
ptr[current] = ptr[i];
current++;
}
}
ptr[current] = 0;
}
int main(int argc, char** argv)
{
char str[256] = {0,};
gets(str);
removeDuplicates(str);
printf("%s\n", str);
return 1;
}
How can i do this in one loop
You can do this in one pass with something like:
This removes duplicates in one single pass, using two pointers that advance independently through the string:
The
srcpointer advances by one each iteration of the loop. A character is copied fromsrctodstand thedstpointer is advanced only if the character has not been seen before (using thefoundarray). The output is:Note the
"assumes 8-bit char"comment – this is fine where you know the character set is ASCII (or any other 8-bit character set) but it may not be portable to more exotic implementations. You just have to ensure that there are enough elements in thefoundarray for all of your characters. For example, a 10-bitchartype would need 1024 elements (210 = 1024).