2

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' || .... 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.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335

3 Answers3

5

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 is true if either x or y is non-zero. So your test is essentially equivalent to

if (a == 1)
Barmar
  • 741,623
  • 53
  • 500
  • 612
3

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 == '?' )  {
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
1

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.)

Adrian Mole
  • 49,934
  • 160
  • 51
  • 83