Search code examples
ccs50c-stringsfunction-definition

How can I convert chars(pointer) to strings in C - to be used in strcmp


I am trying to create a function that takes a string as an input and compares each character to each other to ensure they don't repeat.

The string consists of 26 alpha characters The goal is to compare the 26 characters to each other to ensure that none repeat. To do that, I want to use strcmp (because I know not of any function that compares chars).

To do that, I first need to convert the chars in my code to strings in order to compare them. How can I go about doing that?

This is my function:

bool is_valid_key(string verify)
int a = 0;
    int b = 0;
    string s1 = verify[a], s2 = verify[b];
        for ( a = 0; a < verify[a]; a++)
    {
        if (strcmp( s1, s2) == 0)
        return 0;
    }
   return 1;

Solution

  • You do not need to compare strings for this test, just single char values. char values can be compared with == and != so you could write 2 nested loops:

    bool is_valid_key(const char *key) {
        for (int a = 0; key[a] != '\0'; a++) {
            for (int b = 0; b < a; b++) {
                // if 2 characters match, the key is not valid
                if (key[a] == key[b])
                    return false;
            }
        }
        // all characters are different: key is valid
        return true;
    }
    

    The problem with this approach is you do not test the key length, nor that it is only composed of letters.

    Here is a different approach:

    // check that key contains 26 lowercase letters without duplicates
    bool is_valid_key(const char *key) {
        unsigned long mask = 0;
        for (int i = 0; key[i] != '\0'; i++) {
            if (key[i] < 'a' || key[i] > 'z') {
                // invalid character
                return false;
            }
            // this assumes that letters are contiguous, which is true for ASCII
            unsigned long bit = 1UL << (key[i] - 'a');
            if (mask & bit) {
                // duplicate character
                return false;
            }
            mask |= bit;
        }
        // check that all 26 letters have been set
        return mask == (1UL << 27) - 1;
    }