Home > Software design >  Returning Unique Character Array (Unique String) from User Input
Returning Unique Character Array (Unique String) from User Input

Time:11-29

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);
}

CodePudding user response:

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.

  • Related