0

Somewhere in my program I get these outputs:

ee 

or:

thht 

Basically I want to remove the duplicates to obtain e or th. I got this code:

j = 0; for (i = 1; i < strlen(erros); i++) { if (erros[j] != erros[i]) { erros[j+1] = erros[i]; j++; } } 

This code gives me e and tht. If in the first case its OK, in the second its not. I believe it is due because I don't have a sorted array.

Is there a way, without sorting the array and using the above code, to obtain the desired output?

1

1 Answer 1

3

You can create an array of flags, one for each possible character value. The first time you encounter a particular character value, set the flag. The next time you encounter that value, the flag will be set, indicating that you can remove that character.

Along the lines of (untested):

int flags[1 << CHAR_BIT]; memset(flags, 0, sizeof(flags)); j = 0; for (i = 0; i < strlen(erros); i++) { erros[j] = erros[i]; // Always copy, it's simpler if (!flags[erros[i]]) { j++; } flags[erros[i]] = 1; // Always set the flag, it's simpler } erros[j] = '\0'; 

Note: You are forgetting to set the NULL terminator in your string.

Sign up to request clarification or add additional context in comments.

1 Comment

@Favolas: No worries. If this has solved your problem, please could you "accept" this answer?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.