liveBook · Manning

Strcspn

As explained in Modern C, Third Edition

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

strcspn returns the length of the initial segment of its first string containing no character from its second string. The second argument therefore acts as a set of stopping characters. section 6.1.5 section 8.5

Stopping at a delimiter

With `strcspn("abc:def", ":")`, the result is `3`: the initial segment is `"abc"`, and scanning stops before the colon. Include `<string.h>` when declaring or using the function. section 6.1.5 section 8.5

Use strcspn under these validity constraints:

  • Pass genuine null-terminated strings for both parameters; applying string functions to a non-string can cause excessive scanning, boundary violations, or data corruption. section 6.1.5
  • Expect a `size_t` result, matching the function prototype `size_t strcspn(char const s1[static 1], char const s2[static 1]);`. section 6.1.5
  • Use strspn when the desired initial segment contains characters from the supplied set rather than excluding them. section 6.1.5 section 8.5
size_t strlen(char const s[static 1]);
char*  strcpy(char target[static 1], char const source[static 1]);
char*  strdup(char const s[static 1]);
char*  strndup(char const s[static 1], size_t n);
signed strcmp(char const s0[static 1], char const s1[static 1]);
signed strcoll(char const s0[static 1], char const s1[static 1]);
char* strchr(const char s[static 1], int c);
size_t strspn(const char s1[static 1], const char s2[static 1]);
size_t strcspn(const char s1[static 1], const char s2[static 1]);

Inspect the declared interface for strcspn alongside related C string functions. section 6.1.5

How Modern C, Third Edition covers it

How deep it goes
Defines the returned length, prototype, and termination requirement but does not detail implementation internals.
Examples
Uses delimiter-oriented scanning and places the function beside strspn in numeric-string parsing.
What it assumes
Assumes familiarity with C strings and teaches that both arguments must be null-terminated.
What you can do after
Apply it via the C standard library to measure a prefix that excludes characters from a specified string.
How it connects
Contrasts with strspn and belongs to the string-search functions used alongside strtoul.

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.