So, my main task is to return a character array consisting of unique characters, but in the same order as they are within the user input. I have worked on a function below that seems feasible, but returns nothing whenever I type anything in as input.
Joooooooe should return Joe. Rooooobert should return Robert. Aalllbbert should return Albert. Likewise, Duuccck should return Duck.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void unique_string(char* new_string) {
char updated_string[251];
int counter = 0;
for (int i = 0; i < strlen(new_string); ++i) {
char new_char = new_string[i];
char *potential_candidate;
potential_candidate = strchr(updated_string, new_char);
if (potential_candidate != NULL) {
updated_string[counter] = *potential_candidate;
counter++;
printf("%c", *potential_candidate);
}
}
}
int main() {
char new_string[251]; //max of 250 characters
scanf("%s", new_string);
unique_string(new_string);
}
There are 26 letters in the English alphabet.
You can easily create an array of
boolvalues representing if the characters has been seen before or not (initialized to allfalse).For each character of the input, convert it to an index, where
'a'is0,'b'is1, and so on. Then check the current characters position in the "have been seen" array. If it'sfalseprint the character and set it totrue. Otherwise skip the printing and continue to the next character in the input.Use
isalphato make sure the character is a letter, and use eithertolowerortoupperto make it case-independent.