0

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);
}
ArbIn
  • 43
  • 5
  • Step 1: maintain a lookup table (array) of size 256, which will mark every character encountered in the input string so far. –  Nov 28 '22 at 15:58
  • Step 2: sweep the input string, and for every character which appears in it, check if that character is already marked 'encountered' in the lookup table. If not encountered, then mark it in the lookup table as such, and add it to the output string. –  Nov 28 '22 at 15:59
  • "Returning" is not the same thing as *printing*. If printing is indeed what you want your function to do, then make sure to print a newline after the last character, and / or to `fflush(stdout)`. – John Bollinger Nov 28 '22 at 15:59
  • Note that you may allocate the output string to be of the same length as the input string, because it is never going to require more memory space. –  Nov 28 '22 at 16:00
  • Lastly, do not forget to add a 0 (null character) at the end of the output string. –  Nov 28 '22 at 16:00

1 Answers1

2

There are 26 letters in the English alphabet.

You can easily create an array of bool values representing if the characters has been seen before or not (initialized to all false).

For each character of the input, convert it to an index, where 'a' is 0, 'b' is 1, and so on. Then check the current characters position in the "have been seen" array. If it's false print the character and set it to true. Otherwise skip the printing and continue to the next character in the input.

Use isalpha to make sure the character is a letter, and use either tolower or toupper to make it case-independent.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • Have made the changes that you suggested. I really appreciate your input. The answer has been Accepted. – ArbIn Nov 28 '22 at 17:24