简体   繁体   中英

Does anyone know what is the best way in C to check if a character is in a string?

I have a string for example "ABCDEFG.......", and I want to check if a certain character is in this string or not (the string also contains the newline character). I have the following code, but it doesn't seem to be working. Anyone have any better ideas?

Currently using the strchr to check if it comes out to be NULL, meaning the current char in the loop, is NOT present in the valid_characters variable.

bool check_bad_characters(FILE *inputFile)
{
    int c;
    char valid_characters[28] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ ";
    while ((c = fgetc(inputFile)) != EOF) {   
        char charC = c + '0';
        if (strchr(valid_characters, c) == NULL && strncmp(&charC, "\n", 1) != 0)
        {
            // This means that there was a character in the input file
            // that is not valid.
            return false;
        }    
    }
    return true;
}

Your code considers \n to be a valid character, so put it in the list of valid characters instead of handling it separately. Your routine can be simply:

bool check_bad_characters(FILE *inputFile)
{
    int c;
    while ((c = fgetc(inputFile)) != EOF)
        if (!strchr("ABCDEFGHIJKLMNOPQRSTUVWXYZ \n", c))
            return false;
    return true;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM