C String strcspn() Function

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

What You’ll Learn

The strcspn() function measures how many leading characters in a string belong to a prefix that contains none of the characters in a reject set. It stops at the first “forbidden” character—ideal for finding tokens before delimiters.

01

Prefix Length

size_t result.

02

Reject Set

Stop chars.

03

Not In Set

Complement span.

04

Parse Tokens

Before @ , ;

05

string.h

Standard C.

06

vs strspn

Accept set.

Definition and Usage

Think of strcspn as complement span: it counts characters from the start of s until it hits any character listed in reject. The return value is that count—not including the stopping character.

If every character in s avoids the reject set, the function returns strlen(s). Pair it with pointer arithmetic to extract substrings without copying: the token is the first len bytes at s.

💡
Beginner Tip

Memory trick: strcspn = complement spn (span). strspn counts chars in the set; strcspn counts chars not in the set.

📝 Syntax

Standard C declaration:

C
size_t strcspn(const char *s, const char *reject);

Parameters

  • s — null-terminated string to scan from the beginning.
  • reject — C-string of characters that terminate the span (delimiter set).

Return Value

  • Number of characters in the initial segment of s that contain no characters from reject.
  • Range: 0 to strlen(s).

Header

  • #include <string.h>

⚡ Quick Reference

srejectstrcspn result
"Hello, World!""aeiou"1 (stops at 'e')
"user@mail.com""@"4 (username length)
"alpha,beta"",;"5 (token before comma)
"nodigits""0123456789"8 (full string)
extract tokendelimiters%.*s with (int)len, s
Measure
len = strcspn(s, reject);

Prefix len

Token
printf("%.*s", (int)len, s);

Print slice

Advance
s += len; if (*s) s++;

Past delim

Opposite
strspn(s, accept)

In-set span

Examples Gallery

Compile with gcc strcspn.c -std=c11 -o strcspn. Return type is size_t—use %zu to print.

📚 Getting Started

Count characters until the first member of a reject set appears.

Example 1 — Length Before First Vowel

In "Hello, World!", how many leading characters are not vowels?

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

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

    size_t length = strcspn(text, vowels);

    printf("Chars before first vowel: %zu\n", length);
    printf("Prefix: %.*s\n", (int)length, text);

    return 0;
}

How It Works

'H' is not a vowel, so the count is 1. The next character 'e' is in the reject set, so scanning stops. The prefix is just "H".

Example 2 — Extract Username Before @

Use strcspn to find the length of the local part of an email.

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

int main(void) {
    const char *email = "alex@codetofun.com";
    size_t user_len = strcspn(email, "@");

    printf("Username (%zu chars): %.*s\n", user_len, (int)user_len, email);

    return 0;
}

How It Works

Scanning stops at '@' after four characters. %.*s prints exactly that many bytes without needing a temporary copy.

📈 Practical Patterns

CSV fields, comparison with strspn, and simple token loops.

Example 3 — First CSV Field

Read characters until a comma or semicolon delimiter.

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

int main(void) {
    const char *row = "apple,banana,cherry";
    size_t field_len = strcspn(row, ",;");

    printf("First field: %.*s\n", (int)field_len, row);

    return 0;
}

How It Works

The reject set ",;" lists delimiters. strcspn returns 5—the length of "apple" before the comma.

Example 4 — strcspn() vs strspn()

See complement span side by side on the same string.

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

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

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

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

    return 0;
}

How It Works

strspn skips whitespace (chars in the accept set). Then strcspn measures the word (chars not in whitespace). Together they trim and slice input efficiently.

Example 5 — Walk Comma-Separated Tokens

Advance through the string using repeated strcspn calls.

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

int main(void) {
    const char *cursor = "red,green,blue";
    const char *delim = ",";

    while (*cursor) {
        size_t len = strcspn(cursor, delim);
        printf("Token: %.*s\n", (int)len, cursor);
        cursor += len;
        if (*cursor) {
            cursor++;  /* skip delimiter */
        }
    }

    return 0;
}

How It Works

Each iteration prints a token of length len, skips past it, then skips one delimiter byte. For complex parsing, strtok wraps similar logic but modifies the string.

🚀 Common Use Cases

  • Delimiter parsing — measure tokens before ,, ;, or |.
  • Input validation — count leading non-digit characters before a number.
  • Path segments — length of name before / or \.
  • Trim + extract — combine with strspn to skip padding.
  • Custom lexers — scan identifiers until operator symbols.

🧠 How strcspn() Works

1

Start at s[0]

Initialize count to 0.

Scan
2

Check reject set

If current char appears in reject, stop.

Test
3

Increment and continue

Otherwise count++ and move to next char until '\0'.

Count
=

size_t len

Length of prefix with no reject characters.

📝 Notes

  • Return type is size_t—print with %zu.
  • Empty reject yields length of entire s.
  • Time complexity is O(n×m) naive; libraries often optimize with lookup tables.
  • Does not allocate memory or null-terminate a slice—use %.*s or copy if needed.
  • For a single delimiter, strchr returns a pointer; strcspn returns a length.

⚡ Optimization

For a fixed small reject set called many times, a 256-byte bitmap of forbidden characters can beat repeated scans of reject. For occasional parsing, the standard strcspn is clear and fast enough.

Conclusion

strcspn() returns how many initial characters of s avoid the reject set. Use it to measure tokens before delimiters and combine with strspn() for full parsing pipelines.

Continue with strxfrm() for locale-aware sort keys, or review strspn() for the complementary accept-set span.

💡 Best Practices

✅ Do

  • Use %.*s with the returned length to print tokens
  • Pair with strspn to skip separators and padding
  • Cast to int for %.*s when length fits in int
  • Include every delimiter character in reject
  • Advance pointers after each token in loops

❌ Don’t

  • Confuse strcspn (not in set) with strspn (in set)
  • Assume the stopping character is included in the length
  • Print with %s on a slice without length limits
  • Pass NULL pointers
  • Forget that reject is a C-string, not a single char only

Key Takeaways

Knowledge Unlocked

Five things to remember about strcspn()

Use these points when parsing strings in C.

5
Core concepts
📝 02

Reject Set

Stop chars.

Input
🔢 03

Not In Set

Complement.

Rule
📈 04

Parse

Tokens, CSV.

Use case
💬 05

vs strspn

Accept set.

Compare

❓ Frequently Asked Questions

strcspn() returns the length of the longest initial segment of s that contains no characters from the reject set. It stops at the first character in s that appears in reject—or at the end of s if none match.
size_t strcspn(const char* s, const char* reject); Include <string.h>. s is the string to scan. reject is a C-string listing characters to stop on (the delimiter set).
strspn(s, accept) counts leading characters that ARE in accept. strcspn(s, reject) counts leading characters that are NOT in reject. They are complementary: strspn skips allowed chars; strcspn skips until a forbidden char.
It returns strlen(s)—the length of the entire string. Every character belongs to the initial segment with no reject matches.
If reject points to an empty string, strcspn returns the length of s (the whole string), because no character in s can match an empty reject set.
Call len = strcspn(cursor, ",;"). The first len bytes of cursor form a token with no delimiters. Advance with cursor += len, skip the delimiter, and repeat—often paired with strspn to skip separators.
Did you know?

POSIX provides strpbrk(s, accept) to find the pointer to the first character in s that matches any char in accept. strcspn tells you how far you can read before that happens—length vs pointer, both useful in parsers.

Continue the String Functions Series

Measure delimiter-free prefixes with strcspn(), then explore locale sort keys with strxfrm().

Next: strxfrm() →

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