A structured lesson workspace with readable content, hands-on examples, and a clean path to completion.
strcspn returns the length of the initial segment of a string that contains none of the characters from a second string. The name is hard to remember. Think of it as "string complement span." It answers: how many characters can I read from the start before I hit any of these delimiters? This is the function you use to find the length of a token without modifying the input, unlike strtok.
#include <stdio.h>#include <string.h>int main(void) {const char *input = "username=admin;password=secret";const char *delims = "=;";size_t len = strcspn(input, delims);printf("First token length: %zu\n", len);printf("First token: %.*s\n", (int)len, input);const char *rest = input + len;printf("Remaining: \"%s\"\n", rest);return 0;}
strcspn scanned "username=admin;password=secret" and found that the first 8 characters ("username") contain neither '=' nor ';'. The 9th character is '=', which is in the delimiter set. The function returned 8. We used the %.*s format to print exactly that many characters without needing a null terminator at the boundary. The input string is unmodified.
#include <stdio.h>#include <string.h>int main(void) {const char *csv = "red,green,blue";const char *pos = csv;while (*pos) {size_t len = strcspn(pos, ",");printf("Token: %.*s\n", (int)len, pos);pos += len;if (*pos == ',') pos++;}return 0;}
No modification to the input. No static state. Thread-safe. Re-entrant. The const qualifier on csv is preserved because we never write to it. This pattern is strictly better than strtok for read-only tokenization. The only downside is that you must handle the delimiter advancement yourself, which is three lines of code.
strcspn and its complement strspn are the building blocks of manual parsers. They let you measure tokens without cutting them. Next: strchr, the single-character search that strrchr builds upon.
Finish the lesson once you have worked through the material. This awards ★ 20 XP.