C String strspn() Function

Beginner
⏱️ 10 min read
📚 Updated: Jul 2026
🎯 5 Examples
<string.h>

What You’ll Learn

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.

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.

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

⚡ Quick Reference

sacceptResult
"Hello, World!"letters A–Z, a–z5 (Hello)
" text"" \t"3 (spaces)
"123abc""0123456789"3
",hello"letters0 (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

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!".

C
#include <stdio.h>
#include <string.h>

int main(void) {
    const char *text = "Hello, World!";
    const char *letters =
        "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";

    size_t length = strspn(text, letters);

    printf("Alphabet prefix length: %zu\n", length);
    printf("Prefix: %.*s\n", (int)length, text);

    return 0;
}

How It Works

Scanning stops at the comma. The first five bytes are all letters, so strspn returns 5.

Example 2 — Skip Leading Whitespace

Find how many spaces or tabs appear before real content.

C
#include <stdio.h>
#include <string.h>

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

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

    printf("Padding: %zu chars\n", pad);
    printf("Content starts at: [%s]\n", line + pad);

    return 0;
}

How It Works

Six bytes are space or tab. Adding pad to the pointer skips the padding without copying the string.

📈 Practical Patterns

Digits, comparison with strcspn, and a mini parser.

Example 3 — Leading Digit Run

Count digits at the start of a mixed string.

C
#include <stdio.h>
#include <string.h>

int main(void) {
    const char *value = "12345px";

    size_t digits = strspn(value, "0123456789");

    printf("Digit count: %zu\n", digits);
    printf("Number part: %.*s\n", (int)digits, value);
    printf("Suffix:      %s\n", value + digits);

    return 0;
}

How It Works

strspn stops at 'p' because it is not in the digit accept set. Useful for simple unit suffix parsing.

Example 4 — strspn() vs strcspn()

Trim padding, then measure the next word token.

C
#include <stdio.h>
#include <string.h>

int main(void) {
    const char *s = "  hello world";

    size_t spaces = strspn(s, " \t");
    size_t word   = strcspn(s + spaces, " \t");

    printf("spaces skipped: %zu\n", spaces);
    printf("word length:    %zu\n", word);
    printf("word:           %.*s\n", (int)word, s + spaces);

    return 0;
}

How It Works

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

How It Works

strspn(p, ",") skips commas between tokens. strcspn(p, ",") measures each token. This is a teaching parser—not a full CSV solution.

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

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

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

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.

💡 Best Practices

✅ Do

  • Print results with %zu
  • Advance pointers with s += strspn(s, accept)
  • Pair with strcspn for token extraction
  • 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

Key Takeaways

Knowledge Unlocked

Five things to remember about strspn()

Use these points when measuring accept-set spans in C.

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

Continue the String Functions Series

Measure accept spans with strspn(), then learn reject spans with strcspn().

Next: strcspn() →

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