C Reference ยท string.h
C strspn() and strcspn() functions
Reference for C strspn() and strcspn(): measure the initial run of accepted or rejected characters, validate input, trim newlines and tokenize without modifying a string.
strspn() returns the length of the initial part of a string made up only of characters from a given set. strcspn() returns the length of the initial part that contains none of the characters in the set. Both return an index, which is often exactly what you need: where does the digits-only prefix end, or where is the first newline?
Neither function modifies anything, which makes them a safe alternative to strtok.
#include <string.h> size_t strspn(const char *s, const char *accept); size_t strcspn(const char *s, const char *reject);
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.
Syntax
size_t strspn(const char *s, const char *accept); size_t strcspn(const char *s, const char *reject);
| Name | Description |
|---|---|
s |
The string to examine. |
accept |
(strspn) The set of characters allowed in the prefix. |
reject |
(strcspn) The set of characters that end the prefix. |
Returns: the length of the matching prefix. If the whole string qualifies, the result equals strlen(s), so s[result] is the terminator.
Errors / undefined behavior: both arguments must be terminated strings; NULL is undefined.
Usage notes
- The set is a list of characters, not a string to match.
strspn(s, "ab")accepts any mix ofaandb. s[strcspn(s, "\n")] = '\0'is the standard one-line way to strip the newline from a line read byfgets. It is safe when no newline is present, because the index then points at the existing terminator.- Validation:
s[strspn(s, set)] == '\0'tests that every character is in the set. Check for an empty string separately if empty is not valid. strcspn(s, "")equalsstrlen(s)because nothing is rejected, andstrspn(s, "")is 0.- Complexity is roughly the prefix length times the set size. Implementations often build a lookup table, so large sets stay fast.
- No state, no modification. Unlike
strtokthey work on string literals and are safe in threads. - Finding one character is simpler with
strchr; finding a pointer to the first of several characters isstrpbrk, whichstrcspncan emulate by index. - Bytes, not Unicode. Multibyte characters are treated as separate bytes, so listing a non-ASCII character in the set matches each of its bytes.
Related
strpbrk,strtok,strchr,fgets,strlen- Lessons: String functions, User input