C++ String strspn() Function

Beginner
⏱️ 10 min read
📚 Updated: Jul 2026
🎯 5 Examples
Accept-set span

What You’ll Learn

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.

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.

📝 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.

⚡ Quick Reference

FunctionStops when…Counts…
strspn()Char is not in accept setLeading allowed chars
strcspn()Char is in reject setLeading disallowed chars
strpbrk()Any reject char foundPointer to first match
isdigit loopNon-digitManual validation
Scan
strspn(s, set)

Accept span

Spaces
strspn(s, " \t")

Leading pad

Digits
strspn(s, "0123456789")

Numeric prefix

Include
#include <cstring>

Header file

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.

C++
#include <iostream>
#include <cstring>

int main() {
    const char* line = "   \t  Hello";

    std::size_t pad = std::strspn(line, " \t");

    std::cout << "Leading whitespace: " << pad << " chars\n";
    std::cout << "Text starts at:     \"" << (line + pad) << "\"\n";

    return 0;
}

How It Works

Three spaces, one tab, and two more spaces are all in the accept set. Scanning stops at 'H', so line + pad points to the trimmed content.

Example 2 — Initial Letters and Spaces

See why special symbols stop the span early—as in the classic C++ example.

C++
#include <iostream>
#include <cstring>

int main() {
    const char* text = "C++ is awesome!";
    const char* lettersAndSpace =
        "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ";

    std::size_t span = std::strspn(text, lettersAndSpace);

    std::cout << "Accepted prefix length: " << span << "\n";
    std::cout << "Prefix:                 ";
    for (std::size_t i = 0; i < span; ++i) {
        std::cout << text[i];
    }
    std::cout << "\n";
    std::cout << "Stopped at:             '" << text[span] << "'\n";

    return 0;
}

How It Works

C is a letter and counts. The next character + is not in the letters-and-space set, so the span ends at length 1—not the whole phrase.

📈 Practical Patterns

Compare with strcspn, trim tokens, and validate numeric prefixes.

Example 3 — strspn() vs strcspn()

Complementary rules on the same string and delimiter set.

C++
#include <iostream>
#include <cstring>

int main() {
    const char* data = "12345abc";

    std::size_t digitsOnly = std::strspn(data, "0123456789");
    std::size_t notDigits = std::strcspn(data, "0123456789");

    std::cout << "strspn (digits):  " << digitsOnly << "\n";
    std::cout << "strcspn (digits): " << notDigits << "\n";
    std::cout << "Same?             "
              << std::boolalpha << (digitsOnly == notDigits) << "\n";

    return 0;
}

How It Works

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;
}

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;
}

How It Works

Scanning stops at the first non-digit. Useful for quick input checks before calling functions like atoi on the numeric prefix.

🚀 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.

📝 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.

⚡ 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.

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.

💡 Best Practices

✅ Do

  • Use strspn(s, " \t") to measure leading whitespace
  • Combine with strcspn after skipping padding
  • Build accept sets explicitly ("0123456789", " \t\n")
  • Remember return 0 means first char is not allowed
  • 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

Key Takeaways

Knowledge Unlocked

Five things to remember about strspn()

Use these points when scanning accepted character prefixes.

5
Core concepts
🚫 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.

Series Complete: C String Functions

You finished the strspn() tutorial—all 15 C-string function guides are now available in the new layout.

C++ Interview Programs →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

6 people found this page helpful