简体   繁体   中英

Checking for different characters in C

I wanted to know if there is a way in c to check, for example in a for function if a variable is equal or unequal to certain characters without having to repeat each time an equality check. If I am not wrong, checking equality this way is incorrect:

if (a == ('\n' || '\t' || ' ' || ',' || '.' || ';' || ':' || '!' || '?')) {
     execute certain action;
}

you would need to have an endless chain of a == '\n' || a == '\t' ||... a == '\n' || a == '\t' ||... . I was wondering if there was a shorter (and cleaner) way to check equality for a list of symbols, because when instead of a you have something more descriptive, this code becomes a mess. Also, if you could explain to me why the first part is wrong, I would be grateful.

You can use strchr() to search for the character in a string.

#include <string.h>

if (strchr("\n\t ,.;:!?", a) != NULL) {
    // execute certain action
}

The reason why your attempt doesn't work is because the || operator is combining all its operands using the boolean OR operation, and returns a boolean value. x || y x || y is true if either x or y is non-zero. So your test is essentially equivalent to

if (a == 1)

Just write a function similar to the following

#include <string.h>

//...

int is_separatison( char c )
{
    const char *s = "n\t ,.;:!?";

    return c != '\0' && strchr( s, c ) != NULL;
}

The same expression you can use in an if statement. Only you can remove the comparison with the zero character if you know that the checked character is not a zero character.

const char *s = "n\t ,.;:!?";

if ( strchr( s, c ) != NULL )
{
    // do something
}

As for showed by you if statement then it shall be rewritten like

if ( a == '\n' || a == '\t' || a == ' ' || a == ',' || 
     a == '.'  || a ==';'   || a == ':' || a == '!' || a == '?' )  {

You can use the strchr function, which checks for the first occurrence of a character in a given string (which can be a string literal). If it's not found, the function returns a NULL (zero) value.

So, in your case, you could do this:

if (strchr("\n\t ,.;:!?", a) == NULL) {
    // Action when NOT found
}
else {
    // Action when found
}

(You need to #include <string.h> somewhere in your source to use this function.)

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