A structured lesson workspace with readable content, hands-on examples, and a clean path to completion.
strspn returns the length of the initial segment of a string consisting entirely of characters from a second string. It is the complement of strcspn. Where strcspn asks "how far until I hit a delimiter?", strspn asks "how far can I go while staying within this allowed set?" Use it to validate that a prefix contains only digits, only hex characters, or only whitespace.
#include <stdio.h>#include <string.h>int main(void) {const char *input = "12345abc";size_t digit_len = strspn(input, "0123456789");printf("Leading digits: %.*s (length %zu)\n",(int)digit_len, input, digit_len);const char *padded = " hello";size_t ws_len = strspn(padded, " \t\n");printf("Whitespace prefix length: %zu\n", ws_len);printf("After whitespace: \"%s\"\n", padded + ws_len);return 0;}
The whitespace-skipping pattern is the most common use. Instead of a manual while loop checking isspace, strspn gives you the count in one call. Add that count to the pointer and you are at the first non-whitespace character. Clean, fast, no branching.
strspn and strcspn together give you a complete prefix-measurement toolkit. One measures matches, the other measures non-matches. Between them, you can build any tokenizer or validator without modifying the input. Next: strcat and strncat, for appending strings, and why the bounded version matters.
Finish the lesson once you have worked through the material. This awards ★ 20 XP.