strspn returns the length of the initial segment of one null-terminated string whose characters all occur in a second string. Include <string.h> and use its size_t result. section 8.5 section 6.1.5
Skipping leading whitespace
#include <stdio.h> #include <string.h> int main(void) { char const input[] = " \t\n42"; size_t const count = strspn(input, " \f\n\r\t\v"); printf("%zu\n", count); } The call returns 3: the initial space, tab, and newline belong to the allowed-character string. A parser can then continue at input + count, as the strtoul implementation does after skipping whitespace. section 8.5 section 6.1.5
Both arguments must be strings: each must be terminated by a zero character. Passing a character array without that terminator can make the function read beyond the array boundary and cause slow execution, a segmentation violation, or data corruption. section 6.1.5
Related behavior:
- strcspn counts the initial characters that do not occur in the second string. section 8.5
- Use memchr and explicit length information instead when the character array may not be null-terminated. section 6.1.5
