In C++, strcspn() looks only at the start of a C-string and counts how many characters in a row are not in a reject set. It stops at the first space, comma, or other character you put in that set.
Both arguments are required. The result is a length, and it is also the index of the first rejected character. It is 0 when the first character is rejected. strspn() counts characters that are in the set instead. Include <cstring>.
Syntax
The second string lists the characters that stop the count.
C++
strcspn("Hello, world", " ,");
Call
What it does
strcspn("Hello, world", " ,")
Counts letters until the first space or comma. The result is 5.
How many starting characters are not in the reject set. That is also the index of the first rejected character.
0
The first character is in the reject set.
C++ Examples
Example 1 — Basic strcspn()
Find where invalid characters start.
C++
#include <iostream>
#include <cstring>
int main() {
const char* text = "abcde312$#@";
const char* reject = "*$#";
std::size_t n = strcspn(text, reject);
std::cout << "Safe length: " << n << '\n';
std::cout << "First reject at index: " << n << '\n';
return 0;
}
Output
Safe length: 8
First reject at index: 8
How It Works
Characters a…2 are not in "*$#".
At index 8, '$' is in the reject set.
Return value 8 is both the safe length and that index.
Example 2 — Length of the First Word
Treat space as a delimiter.
C++
#include <iostream>
#include <cstring>
int main() {
const char* line = "Hello C++ Tutorial";
std::size_t wordLen = strcspn(line, " ");
std::cout << "First word length: " << wordLen << '\n';
std::cout.write(line, wordLen) << '\n';
return 0;
}
Output
First word length: 5
Hello
How It Works
Reject set is just a space.
Count stops before the first space.
cout.write prints those first 5 characters.
Example 3 — No Reject Character
If nothing from the set appears, you get the full length.
C++
#include <iostream>
#include <cstring>
int main() {
const char* text = "CodeToFun";
std::size_t n = strcspn(text, "xyz");
std::cout << "strcspn: " << n << '\n';
std::cout << "strlen: " << std::strlen(text) << '\n';
return 0;
}
Output
strcspn: 9
strlen: 9
How It Works
None of x, y, or z appear.
The span runs to the end of the string.
Result equals strlen(text).
Frequently Asked Questions
strcspn() counts how many characters at the start of a C-string are not in a reject set.
text is the C-string to scan. set is the characters that stop the count.
The number of characters before the first rejected one. That number is also the index of that character. It returns 0 when the first character is rejected.
strcspn() stops at characters in the set. strspn() counts characters that are in the set.
Yes. If no rejected character appears, the result is the length of the string.