samedi 18 juillet 2020

How to check for double characters in a string in C?

I am trying to implement a program for Problem Set 2 of CS50.

My program must accept a single command-line argument and the key itself should be case-insensitive, so whether any character in the key is uppercase or lowercase should not affect the behavior of my program.

If the key is invalid (as by not containing 26 characters, containing any character that is not an alphabetic character, or not containing each letter exactly once), your program should print an error message saying "Key must contain 26 characters".

For valid values, I still get the error message, instead of "Correct". Please see my code below.

I am quite new to programming. Any help would be greatly appreciated. Thanks!

#include <cs50.h>
#include <stdio.h>
#include <ctype.h>
#include <string.h>

bool valid_key(string s);
bool single_letter(string s);

int main(int argc, string argv[])
{
    if (argc != 2)
    {
        printf("Usage: ./substitution key\n");
        return 1;
    }
    else if (! valid_key(argv[1]))
    {
        printf("Key must contain 26 characters.\n");
        return 1;
    }
    printf("Correct\n");

    string plaintext = get_string("plaintext: ");

}

bool single_letter(string s)
{
    for (int i = 0, len = strlen(s); i < len; i++)
    {
        for (int j = i + 1; j < len; i++)
        {
            if (s[i] == s[j] || s[i] == ' ')
            {
                return false;
            }
        }
    }
    return true;
}

bool valid_key(string s)
{
    for (int i = 0, len = strlen(s); i < len; i++)
    {
        if (!isalpha(s[i]) || len != 26 || ! single_letter(s))
        {
            return false;
        }
    }
    return true;
}

Aucun commentaire:

Enregistrer un commentaire