Search code examples
cstringrexx

Is there a C function for comparing a string against a character table?


IBM's REXX language has a function called VERIFY that performs what I am looking for:

Given two strings: string and reference:

returns a number that, by default, indicates whether string is composed only of characters from reference; returns 0 if all characters in string are in reference, or returns the position of the first character in string not in reference.

For example, I want to search a string to ensure that it only contains vowels:

str = "foo bar"        /* search string                     */
ref = "aeiou"          /* reference string                  */
loc = VERIFY(str, ref) /* "1" (in REXX, indexes start at 1) */

Is there a C function that will do this? All I could find so far involves manual testing with each character (lots of OR's) in a loop.


Solution

  • Yes, the strspn() function will do what you want. The details are slightly different from REXX's VERIFY, but you can use it to perform the same tests.

    Specifically, strspn() computes the length of the initial segment of the test string that consists of characters from the specified set. This gives you the (zero-based) index of the first character not in the set, or the length of the string (which is the index of its terminator) if the whole string consists of characters from the specified set. Note that the significance of 0 return value is necessarily different. For strspn(), it indicates that the character at index 0 is not in the set (or, as a special case, that the input string is empty).

    You can tell easily whether the whole string consists of characters from the test set by looking at the value of the character at the returned index:

    char *str = "foo bar";          /* search string                     */
    size_t loc;
    
    loc = strspn(str, "aeiou");       // returns 0
    printf("%d\n", (str[loc] == 0));  // prints  0
    
    loc = strspn(str, "abfor");       // returns 3
    printf("%d\n", (str[loc] == 0));  // prints  0
    
    loc = strspn(str, " abfor");      // returns 7
    printf("%d\n", (str[loc] == 0));  // prints  1