Checking a string for correct characters in c

Is there an easier way to do the following in c?

unsigned short check_str(char *str)
{
    while (*str)
    {
        if (!(*str == ' ' || *str == '(' || *str == ')' ||
              *str == '1' || *str == '2' || *str == 'a' ||
              *str == 'x' || *str == 'b'))
              return 0;
        str++;
     }
     return 1;
 }

      

basically it checks the string for any characters other than the ones listed and returns false if it finds one. is there a simpler function?

+2


source to share


2 answers


You want a standard library function strspn

:

strspn(str, " *(12axb") == strlen(str);

      

It will count characters in str

until it sees the first one, which is not one of the characters in the second argument. That way, if it doesn't find any mismatched characters, it will return the length of the string.



A faster way to write the same, although perhaps less clear, is to check \0

instead of calling strlen

:

str[strspn(str, " *(12axb")] == '\0';

      

+20


source


Paul's answer is definitely what you want for your specific problem, but I just thought I'd add that for a more general character validation problem, you can also easily check character ranges if your strings are ASCII. For example:

if (*str >= '0' || *str <= '9') {
   // *str is a number.
}

      



This can be useful if you have many valid characters in a contiguous range. There are a number of standard library functions (like isalpha) that check for common ranges for you.

0


source







All Articles