Compare character with multiple characters in C

浪尽此生 提交于 2019-12-02 11:17:22

Assuming your 'c1', ... are just a single char constants, you can use:

if ( strchr("12345", ch) != NULL )
    ...

("12345" are c1, c2, ...)

strchr() will, however, also match the implcit trailing NUL terminator ('\0'). If that is a problem, you can compare this value explicitly. As the input string is searched from start, you might want to have the more propable values at the beginning.

Note that strchr does return a pointer to the matching char; just if you need that.

If you can group the values, e.g. "letters", "digits", etc., have a look at ctype.h.

If the values are variables, you can either copy them into an array of char before the compare (do not forget about the trminator!) or hold them in the array anyway: array[0] is c1, ... .

If all this is not possible, you are likely busted with strcpy. You could use this:

// assuming there are always the same variables used.
static const char * const ca[] = { &c1, &c2, ... };

char val;

for ( size_t i = 0 ; i < sizeof(ca) / sizeof(ca[0]) ; i++ ) {
    if ( *ca[i] == val ) {
        // match!
    }
}

You could pack that into a function with some decoration here and there.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!