Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

checking a string for correct characters in c

Tags:

c

string

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?

like image 384
user105033 Avatar asked Apr 26 '26 11:04

user105033


1 Answers

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';
like image 108
Pavel Minaev Avatar answered Apr 29 '26 00:04

Pavel Minaev