liveBook · Manning

Strspn

As explained in Modern C, Third Edition

strspn is a C standard-library function that returns the length of the initial segment containing only characters from a specified string.

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

How Modern C, Third Edition covers it

How deep it goes
Defines the initial-segment rule and prototype, then emphasizes null-termination requirements without discussing implementation internals.
Examples
Demonstrates skipping whitespace before numeric conversion and contrasts string scanning with memchr for unterminated arrays.
What it assumes
Assumes familiarity with C character arrays and teaches that string functions require zero-terminated strings.
What you can do after
Apply it via <string.h> to count an allowed-character prefix during parsing.
How it connects
Connects strspn with strcspn, strtoul, null-terminated strings, string functions, and bounded memory scanning.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Modern C, Third Edition. The section links point to the parts of the book it draws on.