tags:

views:

154

answers:

2

Is there any 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 a string for any characters other then the ones listed and returns false if it finds one. is there a more simple function?

+20  A: 

You want the standard library function strspn:

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

It will count characters in str until it sees the first one that isn't one of the characters in the second argument. Thus, if it doesn't find any non-matching characters, it will return the length of the string.

A faster way to write the same, though perhaps less clear, is to check for \0 instead of calling strlen:

str[strspn(str, " *(12axb")] == '\0';
Pavel Minaev
That is what i'm lookin for :D, strpbrk won't work for this.
+1 I had the same `strspn()` idea, but couldn't figure out how to make it efficient. Good call on that.
Chris Lutz
+1 good one, sir
Johannes Schaub - litb
+1 Top tip and well outlined
zebrabox
A: 

Pavel's answer is definitely what you want for your particular problem, but I just thought I'd add that for the more general problem of validating characters, you can also check for ranges of characters very easily if your strings are ASCII. For example:

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

This might be useful if you have a lot of valid characters in a contiguous range. There are a number of standard library functions (e.g. isalpha) that check the common ranges for you.

Shawn