strpbrk() function in C++

In this guide, you will learn what is strpbrk() function is in C++ programming and how to use it with an example.

1. strpbrk() Function Overview

The strpbrk() function is part of the <cstring> library in C++. It searches the first string (str1) for the first occurrence of any character from the second string (str2) and returns a pointer to the location of the first matching character in str1. If no character from str2 is found in str1, it returns a null pointer.

Signature:

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

Parameters:

- str1: The main string where the search is performed.

- str2: The string containing characters to be searched for in str1.

2. Source Code Example

#include <iostream>
#include <cstring>

int main() {
    const char* string = "Hello, World!";
    const char* chars_to_find = "ol";

    const char* result = strpbrk(string, chars_to_find);

    if(result) {
        std::cout << "First character from 'chars_to_find' found in 'string' is: " << *result << std::endl;
    } else {
        std::cout << "No characters from 'chars_to_find' are present in 'string'." << std::endl;
    }

    return 0;
}

Output:

First character from 'chars_to_find' found in 'string' is: o

3. Explanation

1. We've included the <iostream> header for standard input/output and <cstring> for the strpbrk() function.

2. We initialize two strings: string and chars_to_find. We aim to find the first occurrence in string of any character from chars_to_find.

3. We then use the strpbrk() function to get a pointer to the first occurrence.

4. Depending on whether a match is found or not, we display the appropriate result.

This function is handy when you want to quickly locate any of several characters in a string.


Comments