C Reference ยท string.h
C strpbrk() function
Reference for C strpbrk(): find the first character in a string that matches any character of a set, with examples for separators, vowels and scanning loops.
strpbrk() ("string pointer break") scans a string for the first character that appears anywhere in a second string, and returns a pointer to it, or NULL if none of them occurs. It is like strchr with several characters to look for at once.
The name is cryptic, but the idea is simple: "where is the first separator?" or "does this input contain any forbidden character?"
#include <string.h> char *strpbrk(const char *s, const char *accept);
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.
Syntax
char *strpbrk(const char *s, const char *accept);
| Name | Description |
|---|---|
s |
The string to search. |
accept |
The set of characters to look for. Order does not matter. |
Returns: a pointer to the first character of s that is also in accept, or NULL. The terminators are not compared, so searching for '\0' this way does not work.
Errors / undefined behavior: both arguments must be terminated strings; NULL is undefined.
Usage notes
- Check for
NULLbefore dereferencing, as with all search functions. - It returns a pointer,
strcspnreturns an index.strpbrk(s, set)is equivalent tos[strcspn(s, set)] ? s + strcspn(s, set) : NULL. Use whichever form suits you:strcspnis handy for trimming,strpbrkfor continuing a scan. - To visit every match, advance one character after each hit, as in the loop above, or the same match is found again.
- An empty set never matches, so the result is
NULL. - Const-correctness: like
strchr, the classic prototype returnschar *from aconst char *. In C23, where the generic form is provided, the result keeps the constness of the argument. Store it in aconst char *for const input. - Complexity is linear in the string length times the set size in the simplest implementation.
- Bytes only. Multibyte UTF-8 characters in the set are treated as separate bytes and can match partial characters.
- Not a tokenizer: it does not modify the string. If you want pieces cut out, see
strtok.
Related
strchrandstrrchr,strspnandstrcspn,strstr,strtok- Lessons: String functions, Strings