C++ strpbrk()

The strpbrk() function in C++ searches for a set of characters present in a string in another string.

strpbrk() Prototype

const char* strpbrk( const char* dest, const char* breakset );
char* strpbrk( char* dest, const char* breakset );

The strpbrk() function takes two null terminated byte string: dest and breakset as its arguments. It searches the null terminated byte string pointed to by dest for any character that is present in the string pointed to by breakset and returns the pointer to that character in dest.

It is defined in <cstring> header file.

strpbrk() Parameters

  • dest: Pointer to a null terminated string to be searched.
  • breakset: Pointer to a null terminated string containing the characters to search for.

strpbrk() Return value

  • If the dest and breakset pointer has one or more characters in common, the strpbrk() function returns the pointer to the first character in dest that is also in breakset.
  • If no characters in breakset is present in dest, a null pointer is returned.

Example: How strpbrk() function works

#include <iostream>
#include <cstdio>

using namespace std;

int main()
{
    char digits[] = "0123456789";
    char code[] = "ceQasieoLPqa4xz10Iyq";
    char *pos;
    int count = 0;

    pos = strpbrk (code, digits);
    while (pos != NULL)
    {
        pos = strpbrk (pos+1,digits);
        count ++;
    }

    cout << "There are " << count << " numbers in " << code;

    return 0;
}

When you run the program, the output will be:

There are 3 numbers in ceQasieoLPqa4xz10Iyq
Did you find this article helpful?