C++ String strpbrk() Function

Beginner
⏱️ 10 min read
📚 Updated: Jul 2026
🎯 5 Examples
Character-set search

What You’ll Learn

The strpbrk() function scans a C-string and returns a pointer to the first character that belongs to a given set. The name means string span break—where the scan “breaks” because a matching character from the set was found. It is the pointer-based partner of strcspn().

01

Find First

Match in str1.

02

Char Set

Any in str2.

03

char* Return

Or nullptr.

04

vs strcspn

Ptr vs count.

05

Delimiters

, ; space tab.

06

vs strchr

One vs many.

Definition and Usage

In C++, strpbrk() is declared in <cstring>. It walks str1 from the beginning and checks each character against every character stored in str2. The first hit stops the search and returns a pointer into str1 at that position.

Treat str2 as a bag of characters, not a phrase. Passing "aeiou" finds the first vowel. Passing ",;" finds the first comma or semicolon. If nothing matches, you get nullptr.

💡
Beginner Tip

Index of the match is strpbrk(text, set) - text when the result is not null. That equals strcspn(text, set) when a match exists at that position.

📝 Syntax

Function signature and a typical call:

C++
#include <cstring>

const char* strpbrk(const char* str1, const char* str2);

// Example:
const char* p = strpbrk("Hello, World!", "aeiou");
// *p == 'e' when p is not nullptr

Parameters

  • str1 — the C-string to search (must be null-terminated).
  • str2 — a set of characters; any one match in str1 succeeds.

Return Value

Pointer to the first matching character inside str1, or nullptr if no character from str2 appears in str1.

⚡ Quick Reference

FunctionReturnsBest for
strpbrk()Pointer to first matchUse the char or split there
strcspn()Count before first matchPrefix length only
strchr()Pointer to one charFind '@' or '/'
std::find_first_ofIterator in std::stringModern C++ strings
Search
strpbrk(s, set)

First match ptr

Found?
p != nullptr

Null check

Index
p - s

Offset in str1

Include
#include <cstring>

Header file

Examples Gallery

Compile with g++ strpbrk.cpp -std=c++17 -o strpbrk. Always check for nullptr before dereferencing the returned pointer.

📚 Getting Started

Locate the first character from a set and print it.

Example 1 — Find the First Vowel

Search "Hello, World!" for any character in "aeiou".

C++
#include <iostream>
#include <cstring>

int main() {
    const char* text = "Hello, World!";
    const char* vowels = "aeiou";

    const char* result = std::strpbrk(text, vowels);

    if (result != nullptr) {
        std::cout << "First vowel: " << *result << "\n";
        std::cout << "Index:       " << (result - text) << "\n";
    } else {
        std::cout << "No vowel found.\n";
    }

    return 0;
}

How It Works

H is not a vowel; e at index 1 is the first match. The pointer result points into the original string—no new memory is allocated.

Example 2 — Find a Delimiter

Locate the first comma, semicolon, or tab in a config line.

C++
#include <iostream>
#include <cstring>

int main() {
    const char* line = "timeout=30;retries=3";

    const char* delim = std::strpbrk(line, ",;\t");

    if (delim != nullptr) {
        std::cout << "First delimiter: '" << *delim << "'\n";
        std::cout << "Rest of line:    " << delim << "\n";
    }

    return 0;
}

How It Works

The semicolon after 30 is the first character in the delimiter set. Printing delim shows from that character to the end of the string.

📈 Practical Patterns

Relate to strcspn, extract tokens, and handle missing matches.

Example 3 — strpbrk() vs strcspn()

Both locate the same position—one returns a pointer, the other a length.

C++
#include <iostream>
#include <cstring>

int main() {
    const char* data = "user@example.com";
    const char* specials = "@.";

    const char* ptr = std::strpbrk(data, specials);
    std::size_t len = std::strcspn(data, specials);

    std::cout << "strcspn length: " << len << "\n";
    if (ptr != nullptr) {
        std::cout << "strpbrk index:  " << (ptr - data) << "\n";
        std::cout << "Matched char:   " << *ptr << "\n";
    }

    return 0;
}

How It Works

Four characters user precede @. Use strcspn when you only need the prefix length; use strpbrk when you need the character or tail of the string.

Example 4 — Print Token Before Delimiter

Combine strcspn and strpbrk to print the first field.

C++
#include <iostream>
#include <cstring>

int main() {
    const char* csv = "C++,Java,Python";
    const char* separators = ",";

    std::size_t fieldLen = std::strcspn(csv, separators);
    const char* comma = std::strpbrk(csv, separators);

    std::cout << "Field 1: ";
    for (std::size_t i = 0; i < fieldLen; ++i) {
        std::cout << csv[i];
    }
    std::cout << "\n";

    if (comma != nullptr) {
        std::cout << "Next field starts at: " << (comma + 1) << "\n";
    }

    return 0;
}

How It Works

strcspn measures the token; strpbrk finds the comma so you can advance with comma + 1 for the next field.

Example 5 — No Match Returns nullptr

When no character from the set appears, handle the null pointer safely.

C++
#include <iostream>
#include <cstring>

int main() {
    const char* id = "XR-49281";
    const char* found = std::strpbrk(id, "aeiou");

    if (found == nullptr) {
        std::cout << "No vowels in \"" << id << "\"\n";
    } else {
        std::cout << "Vowel found: " << *found << "\n";
    }

    return 0;
}

How It Works

Dereferencing a null return would crash. Always branch on nullptr before using *found or pointer arithmetic.

🚀 Common Use Cases

  • Finding delimiters — commas, spaces, tabs, or punctuation in config lines.
  • Scanning for vowels or symbol classes — first special character in input.
  • Tokenization helpers — locate split points in CSV or path strings.
  • Validation — detect whether forbidden characters appear in an identifier.
  • Pairing with strcspn() — measure prefix, then jump to the delimiter.

🧠 How strpbrk() Works

1

Read str1[i]

Start at the first character of the haystack string.

Scan
2

Search set str2

Check whether current char equals any member of the accept set.

Test
3

Advance or stop

On match, return pointer here; else move to next char until '\0'.

Loop
🔍

Pointer or null

Address of first match inside str1, or nullptr if the scan finishes with no hit.

📝 Notes

  • The returned pointer points into str1—valid only while that memory remains alive.
  • str2 is a character set, not a substring to find as a whole.
  • Always test for nullptr before dereferencing.
  • Case-sensitive: "A" and "a" are different characters.
  • C++ alternative: s.find_first_of("aeiou") on std::string.

⚡ Optimization

For small character sets on short strings, strpbrk is fine. For repeated searches with the same large set, building a lookup table (256-byte bitmap for ASCII) can beat naive nested scans. In application code, prefer std::string algorithms unless you are interfacing with C APIs.

Conclusion

strpbrk() finds the first character in a C-string that belongs to a set. Return value is a pointer into the original text or nullptr. Pair it with strcspn() when you need both prefix length and delimiter location.

Next, learn strrchr() to search for a single character from the right end of a string—useful for file extensions and path separators.

💡 Best Practices

✅ Do

  • Check if (p != nullptr) before using *p
  • Use p - str1 to get a zero-based index
  • Treat str2 as an unordered character set
  • Combine with strcspn for simple tokenizers
  • Include <cstring> and use std::strpbrk

❌ Don’t

  • Dereference a null return from strpbrk
  • Expect str2 to match as a contiguous substring
  • Keep pointers after the source string buffer is freed
  • Use strpbrk when only one character matters—use strchr
  • Forget case sensitivity when matching letters

Key Takeaways

Knowledge Unlocked

Five things to remember about strpbrk()

Use these points when searching C-strings for character classes.

5
Core concepts
🚫 02

nullptr

Not found.

Return
🔄 03

vs strcspn

Ptr vs count.

Compare
04

Char Set

Any in str2.

Input
📍 05

Index

p - str1.

Pattern

❓ Frequently Asked Questions

strpbrk() scans str1 from left to right and returns a pointer to the first character that also appears anywhere in str2. The second argument is a set of characters to search for—not a substring. Returns nullptr if no character from str2 occurs in str1.
const char* strpbrk(const char* str1, const char* str2); Include <cstring>. str1 is the string to search; str2 lists characters to find (order and duplicates in str2 do not matter).
A pointer into str1 at the first matching character, or nullptr if none is found. You can dereference the result to read the character, or subtract str1 from the pointer to get the index.
strcspn() returns a count of characters before the first match. strpbrk() returns a pointer to the first match itself. They locate the same position but in different forms: strcspn gives length; strpbrk gives address.
strchr() searches for one specific character. strpbrk() searches for any character from a set in str2—for example any vowel or any delimiter in ",;".
Pass c_str() for the haystack: strpbrk(text.c_str(), "aeiou"). The returned pointer points into the internal buffer of the string; do not use it after the string is destroyed or reallocated.
Did you know?

The “pbrk” in strpbrk stands for break—the scan breaks at the first character from the set. Its complement-length sibling strcspn counts how far you get before that break.

Continue the String Functions Series

Find set matches with strpbrk(), then search from the end with strrchr().

Next: strrchr() →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

6 people found this page helpful