A structured lesson workspace with readable content, hands-on examples, and a clean path to completion.
strpbrk scans a string for the first character that matches any character in a second string. It returns a pointer to that character in the original string, or NULL if no match exists. Think of it as a multi-character strchr. You give it a haystack and a set of needles. It finds the earliest needle in the haystack. This is the function you reach for when you need to find the next delimiter, whitespace, or special character in a parser.
#include <stdio.h>#include <string.h>int main(void) {const char *input = "user@example.com";const char *specials = "@.#!";char *found = strpbrk(input, specials);if (found) {printf("First special char: '%c' at position %ld\n",*found, found - input);printf("Remaining string: \"%s\"\n", found);} else {printf("No special characters found.\n");}return 0;}
The returned pointer points into the original string. It is not a copy. You can use pointer arithmetic (found - input) to compute the index. You can use the pointer directly to process the remainder of the string. The function does not modify the input. It is a pure search operation.
#include <stdio.h>#include <string.h>int main(void) {char line[] = "key=value;path=/tmp;mode=0755";const char *delims = "=;";char *pos = line;while (*pos) {char *next = strpbrk(pos, delims);if (next) {*next = '\0';printf("Token: \"%s\"\n", pos);pos = next + 1;} else {printf("Token: \"%s\"\n", pos);break;}}return 0;}
We overwrite the delimiter with a null terminator to split the string in place. This modifies the original buffer, which is fine when you own it and do not need it intact afterward. The strpbrk call finds the next = or ;, we cut there, and advance past it. This is a lightweight tokenizer that handles multiple delimiter types without the statefulness of strtok.
strpbrk is the right tool when you have a set of characters you care about and you want the first hit. It is faster than calling strchr in a loop for each character. Next: strrchr, which finds the last occurrence of a character, essential for extracting file extensions and path components.
Finish the lesson once you have worked through the material. This awards ★ 20 XP.