The strspn() function measures how many characters at the start of a C-string belong to an accept set. The name means span of characters that are in the set. It stops at the first character not listed in the set—the opposite rule from strcspn().
01
Prefix Count
From start.
02
Accept Set
Allowed chars.
03
size_t Return
Character count.
04
vs strcspn
Accept vs reject.
05
Whitespace
Skip padding.
06
<cstring>
C library function.
Fundamentals
Definition and Usage
In C++, strspn() is declared in <cstring>. It walks str from left to right while each character is found in acceptSet. The return value is how many characters passed that test before the scan stopped.
If the first character of str is not in the set, the result is 0. If the entire string uses only allowed characters, the result equals strlen(str). The accept set is a collection of individual characters, not a substring to match as a block.
💡
Beginner Tip
strspn(" hello", " \t") returns 3 for the three leading spaces. Pair with strcspn to skip whitespace, then read the next word.
Foundation
📝 Syntax
Function signature and a typical call:
C++
#include <cstring>
size_t strspn(const char* str, const char* acceptSet);
// Example:
size_t n = strspn(" trim me", " \t");
// n == 3 (three leading spaces)
Parameters
str — null-terminated C-string to scan.
acceptSet — set of characters that may appear in the initial segment.
Return Value
Returns the number of leading characters in str that are all members of acceptSet.
Cheat Sheet
⚡ Quick Reference
Function
Stops when…
Counts…
strspn()
Char is not in accept set
Leading allowed chars
strcspn()
Char is in reject set
Leading disallowed chars
strpbrk()
Any reject char found
Pointer to first match
isdigit loop
Non-digit
Manual validation
Scan
strspn(s, set)
Accept span
Spaces
strspn(s, " \t")
Leading pad
Digits
strspn(s, "0123456789")
Numeric prefix
Include
#include <cstring>
Header file
Hands-On
Examples Gallery
Compile with g++ strspn.cpp -std=c++17 -o strspn. Each example shows how the accept set controls where counting stops.
📚 Getting Started
Count characters at the start that belong to an accept set.
Example 1 — Count Leading Whitespace
Measure how many spaces and tabs appear before the first non-whitespace character.
When the reject set equals the complement of what you accept at the start, both functions report the same boundary index. strspn frames it as “how many digits”; strcspn as “how many before non-digits.”
Example 4 — Skip Padding, Read a Token
Combine strspn and strcspn to trim and extract one word.
C++
#include <iostream>
#include <cstring>
int main() {
const char* line = " trim me ";
std::size_t skip = std::strspn(line, " \t");
const char* start = line + skip;
std::size_t wordLen = std::strcspn(start, " \t");
std::cout << "Token: ";
for (std::size_t i = 0; i < wordLen; ++i) {
std::cout << start[i];
}
std::cout << "\n";
return 0;
}
📤 Output:
Token: trim
How It Works
strspn skips leading spaces; strcspn on the remainder reads until the next space. This two-step pattern is a simple hand-rolled tokenizer.
Example 5 — Validate a Numeric Prefix
Check how many leading characters are decimal digits.
C++
#include <iostream>
#include <cstring>
int main() {
const char* values[] = { "42px", "100", "9 Lives" };
for (const char* v : values) {
std::size_t n = std::strspn(v, "0123456789");
std::cout << "\"" << v << "\" -> " << n << " leading digit(s)\n";
}
return 0;
}
📤 Output:
"42px" -> 2 leading digit(s)
"100" -> 3 leading digit(s)
"9 Lives" -> 1 leading digit(s)
How It Works
Scanning stops at the first non-digit. Useful for quick input checks before calling functions like atoi on the numeric prefix.
Applications
🚀 Common Use Cases
Skipping whitespace — measure leading spaces and tabs before parsing.
Input validation — verify a prefix contains only digits or hex digits.
Lexer-style scanning — accept runs of letters, then switch rules.
Pairing with strcspn() — trim padding, then read until delimiter.
Teaching span functions — complement to strcspn and strpbrk.
🧠 How strspn() Works
1
Start at str[0]
Initialize counter to zero and read the first character.
Start
2
Membership test
If char is in acceptSet, increment counter; else stop.
Test
3
Advance
Move to next character until mismatch or '\0'.
Loop
#
🔢
Return count
The counter is the accept span length—a size_t with no pointer returned.
Important
📝 Notes
Returns 0 when the first character of str is not in the accept set.
acceptSet is a character set, not a substring pattern.
Both arguments must be valid null-terminated C-strings.
Not part of the C++ STL—it lives in <cstring>.
For complex parsing, prefer std::string utilities or regular expressions.
Performance
⚡ Optimization
Library implementations often use lookup tables for ASCII accept sets. For repeated scans on long buffers, cache results or use dedicated lexers. In typical beginner programs, a single strspn call per line is more than fast enough.
Wrap Up
Conclusion
strspn() counts leading characters that belong to an accept set. Use it to skip whitespace, validate numeric prefixes, and pair with strcspn() for simple tokenization. That completes the core C-string function family in this tutorial series.
Review earlier topics like strcpy(), strcmp(), and strlen(), or continue to C++ interview programs for more practice.
Prefer std::string trim/parse helpers in new C++ code
❌ Don’t
Treat acceptSet as a substring to match literally
Assume the span covers the whole string unless all chars are allowed
Confuse strspn (accept) with strcspn (reject)
Pass non-null-terminated buffers
Forget that + and punctuation often stop letter-only sets
Summary
Key Takeaways
Knowledge Unlocked
Five things to remember about strspn()
Use these points when scanning accepted character prefixes.
5
Core concepts
🔢01
Accept Span
Leading allowed.
Basics
🚫02
Stops Early
Not in set.
Rule
🔄03
vs strcspn
Complement ops.
Compare
✂04
Whitespace
Skip padding.
Parse
📝05
size_t
Length, not ptr.
Return
❓ Frequently Asked Questions
strspn() scans a C-string from the start and counts characters while each one appears in the accept set (second argument). It returns that count—the length of the initial segment consisting only of characters from the set.
size_t strspn(const char* str, const char* acceptSet); Include <cstring>. str is the string to scan; acceptSet is a set of allowed characters (not a substring pattern).
A size_t count of leading characters in str that are all members of acceptSet. If the first character of str is not in the set, it returns 0. If every character of str is allowed, it returns strlen(str).
strspn() counts characters that ARE in the set, stopping at the first character not in the set. strcspn() counts characters that are NOT in the set, stopping at the first character that is in the set. They are complementary span operations.
It is treated as individual characters a, b, and c—not the substring "abc" as a whole. Order and duplicates in the set do not change behavior.
Measuring leading whitespace, verifying that input starts with digits or hex characters, and skipping padding before reading a token with strcspn().
Did you know?
strspn and strcspn were designed as paired primitives: one measures text in a class, the other text not in a class. Together with strpbrk, they form a minimal toolkit for parsing C-strings before strtok or modern parsers.