0

Sorry for the title. Feel free to edit it to anything more clear.

I have a string and I have to check that the first char of this string is equal to at least one between other given char, for example B, Z and K (in my case I've about 10 char to check and they are not classifiable as a range).

I'm doing the check as follows.

if (string[0] == 'Z' || string[0] == 'K' || string[0] == 'B') {
   /* do something... */
}

Is there any easier way to do it?

Zagorax
  • 11,440
  • 8
  • 44
  • 56

4 Answers4

10

One possible approach would be to list your target chars in a string and use strchr

const char* matches = "ZKB...";
if (strchr(matches, string[0]) != NULL) {
    /* do something */
}
simonc
  • 41,632
  • 12
  • 85
  • 103
2
#include <string.h>

char* test = "ZKB";
if (strchr(test, string[0]) != NULL)
{
  // do stuff
}
AllTooSir
  • 48,828
  • 16
  • 130
  • 164
0

put all the charcters to compare with in one string and then store the first charcter of the string in another string and do the following strstr("firstChar","compareset"); if it returns null this mean that the first character of the string isn't from the set

Alaa
  • 539
  • 3
  • 8
  • 29
-1

How about create a array to store the chars which will be checkd... For instance,u got check A,B,C,D these 4 chars if they are in your first string which is given. Then write a function:

int check_first(char *s,char *t){ //string s is given,string t is chars which
                                  // will be checked.
    while(*t++ == *s){//You should leave 1 more byte in array to store '\0'
        return 1;
    }
    return 0;
}
simonc
  • 41,632
  • 12
  • 85
  • 103