C++ Standard Library C++ STL Library

C++ <cstring> - strpbrk() Function



The C++ <cstring> strpbrk() function is used to find the first occurrence of any character of the byte string str2 in the byte string pointed to by str1. The terminating null character is considered as a part of the string but not included in searching.

The function returns pointer to the first occurrence of any character of str2 in str1, or null pointer if none of the characters of str2 is present in str1.

Syntax

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

Parameters

str1 Specify pointer to the null-terminated byte string to be searched in.
str2 Specify pointer to the null-terminated byte string containing the characters to match.

Return Value

Returns pointer to the first occurrence of any character of str2 in str1, or null pointer if none of the characters of str2 is present in str1.

Example:

The example below shows the usage of strpbrk() function.

#include <iostream>
#include <cstring>
using namespace std;
 
int main (){
  char MyStr[100] = "To be, or not to be, that is the question.";
  char * search;
  
  //searching for first occurrences of 
  //any character of ",@#" in MyStr
  search = strpbrk(MyStr, ",@#");

  //displaying the result
  if(search != NULL)
    cout<<"Found at: "<<(search-MyStr+1)<<"\n";
  else
    cout<<"Not Found."<<"\n";

  return 0;
}

The output of the above code will be:

Found at: 6

❮ C++ <cstring> Library