I have piece of code in C which removes any duplicate characters in a string. But I am doing it in two loops and would like it to optimize it 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;
}
gets()
even in test code. Forget it exists; usefgets()
instead. \$\endgroup\$ – Jonathan Leffler Oct 20 '11 at 3:53