The strspn() function measures how many characters at the start of a string belong to an accept set. It is the standard way to skip leading spaces, digits, or letters when parsing text in C.
01
Span len
size_t.
02
Accept set
Allowed.
03
Stops early
First mismatch.
04
Can be 0
No match.
05
string.h
Standard C.
06
vs strcspn
Reject set.
Fundamentals
Definition and Usage
strspn stands for string span. Starting at s[0], it counts consecutive characters that appear in accept. When it hits a character not in the set—or reaches '\0'—it returns the count.
For "Hello, World!" with an alphabet accept string, the result is 5 because 'H' … 'o' match and ',' does not.
💡
Beginner Tip
Think spn = span of allowed chars. Pair strspn (skip padding) with strcspn (read until delimiter) to walk through simple formatted input without heavy parser libraries.
Foundation
📝 Syntax
Standard C declaration:
C
size_t strspn(const char *s, const char *accept);
Parameters
s — null-terminated string to examine.
accept — C-string listing characters that may appear in the initial segment.
Return Value
Number of bytes in the initial segment of s consisting only of characters from accept.
0 if s[0] is not in accept (when s is non-empty).
Header
#include <string.h>
Use %zu with printf for size_t results.
Cheat Sheet
⚡ Quick Reference
s
accept
Result
"Hello, World!"
letters A–Z, a–z
5 (Hello)
" text"
" \t"
3 (spaces)
"123abc"
"0123456789"
3
",hello"
letters
0 (comma first)
Accept span
strspn(s, accept)
Leading run
Skip space
strspn(s, " \t")
Trim left
Reject span
strcspn(s, reject)
Until delim
Find char
strpbrk(s, set)
Pointer
Hands-On
Examples Gallery
Compile with gcc strspn.c -std=c11 -o strspn. Print span lengths with %zu.
📚 Getting Started
Count how many leading characters belong to an accept set.
Example 1 — Initial Alphabet Segment
From the reference: measure the letter prefix of "Hello, World!".
strspn accepts whitespace; strcspn rejects it. Together they extract hello from padded input.
Example 5 — Simple Comma-Separated Token Walk
Alternate skipping separators and reading fields.
C
#include <stdio.h>
#include <string.h>
int main(void) {
const char *csv = "one,two,three";
const char *p = csv;
while (*p) {
p += strspn(p, ",");
if (!*p) break;
size_t len = strcspn(p, ",");
printf("[%.*s] ", (int)len, p);
p += len;
}
printf("\n");
return 0;
}
📤 Output:
[one] [two] [three]
How It Works
strspn(p, ",") skips commas between tokens. strcspn(p, ",") measures each token. This is a teaching parser—not a full CSV solution.
Applications
🚀 Common Use Cases
Left trim — skip spaces and tabs before content.
Numeric prefixes — read leading digits before a suffix.
Charset validation — verify an ID starts with allowed symbols.
Lexer-style scans — consume runs of the same character class.
Pair with strcspn — build small splitters and tokenizers.
🧠 How strspn() Works
1
i = 0
Start at s[0].
Init
2
Is s[i] in accept?
If yes, increment i and continue.
Match
3
Stop on mismatch
Return i when char not in set or at '\0'.
Result
=
🔢
size_t count
Length of leading accept-only segment.
Important
📝 Notes
Returns a length, not a pointer—use s + strspn(...) to advance.
Empty accept yields 0 for non-empty s.
Case-sensitive byte matching—include both cases in accept if needed.
Does not modify s; both arguments are read-only scans.
Complement function: strcspn counts until a reject character appears.
Performance
⚡ Optimization
Library implementations often build a lookup table from accept for O(1) per-character tests. For tiny accept sets in homework-sized strings, the standard function is plenty fast. Profile before hand-rolling bitmap tables.
Wrap Up
Conclusion
strspn() counts how many leading characters belong to your accept set. Use it to skip padding and validate prefixes, then combine with strcspn() to read tokens before delimiters.
Next, learn strcspn() for the complementary reject-set span.
Include both upper and lower case in accept when needed
Include <string.h>
❌ Don’t
Confuse strspn (in set) with strcspn (not in set)
Expect a pointer return value
Pass NULL for either argument
Use %d for size_t on modern compilers
Assume locale-aware character classes without building them explicitly
Summary
Key Takeaways
Knowledge Unlocked
Five things to remember about strspn()
Use these points when measuring accept-set spans in C.
5
Core concepts
🔢01
size_t len
Not ptr.
Basics
📝02
Accept set
Allowed.
Input
🔢03
Can be 0
No lead match.
Edge
📈04
vs strcspn
Complement.
Compare
💬05
Parse aid
Skip pad.
Pattern
❓ Frequently Asked Questions
strspn() returns the length of the longest initial segment of s whose characters all appear in the accept set. It stops at the first character in s that is not listed in accept.
size_t strspn(const char* s, const char* accept); Include <string.h>. s is the string to scan. accept is a C-string listing allowed characters at the start.
strspn(s, accept) counts leading characters that ARE in accept. strcspn(s, reject) counts leading characters that are NOT in reject. Use strspn to skip padding; strcspn to measure tokens before delimiters.
It returns 0. The initial segment length is zero when s[0] is not a member of the accept set.
It returns strlen(s)—the entire string belongs to the initial accept-only segment.
Call n = strspn(cursor, " \t") to skip leading spaces, then use strcspn(cursor + n, ",;") to read the next token. Advance cursor and repeat for simple splitters.
Did you know?
The name strspn is easy to mix up with strstr (find substring) and strpbrk (find any char from a set). Remember: spn returns a span length of leading accept characters— a number you add to a pointer, not an address.