Skip to content
Tutorials Center
My learning

Topics

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?"

C
#include <string.h>

char *strpbrk(const char *s, const char *accept);

Try it

C First match from a set

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.

C Looping over every match, and rejecting input

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

C
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 NULL before dereferencing, as with all search functions.
  • It returns a pointer, strcspn returns an index. strpbrk(s, set) is equivalent to s[strcspn(s, set)] ? s + strcspn(s, set) : NULL. Use whichever form suits you: strcspn is handy for trimming, strpbrk for 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 returns char * from a const char *. In C23, where the generic form is provided, the result keeps the constness of the argument. Store it in a const 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.