AppDividend
Latest Code Tutorials

C++ strpbrk() Function Example | std::strpbrk in C++

0

C++ strpbrk() is an inbuilt function that is used for string handling. It is defined under the string.h header file. The strpbrk() function finds the occurrence of the first character in the first string with the specified character of the second strings. Both the strings are passed as arguments. Terminating null characters are not considered. It searches the specified characters of a string in another string.

C++ strpbrk() Function

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

Syntax

char *strpbrk(const char *str_var1, const char *str_var2);

Here str_var1 and str_var2 are the two strings on which all the operations are done.

Parameters

It takes two parameters. The first one is the str_var1 which is a string in which the searching will be done or we can use scanning will be done. Second, the is the str_var2 which contains the set of characters that will be searched in the str_var1 string.

Return Value

It returns the pointer of the character in the first string which matches one of the characters of the second string. In all other cases, it returns NULL.

Example programs on strpbrk() function in C++

Write a program to show the working of the strpbrk() function.

#include <iostream>
#include <string.h>

using namespace std;

int main()
{
  char str_var1[] = "BigFanOfLionelMessi";
  char str_var2[] = "Lionel";
  char *k;
  k = strpbrk(str_var1, str_var2);
  if (k != 0)
  {
    cout << "Matching character:" << *k;
  }
  else
  {
    cout << "Error! Character not found";
  }
}

Output

Matching character: i

Write a program to pass a set of character which is not present in another string using strpbrk() function and show the output.

See the following code.

#include <iostream>
#include <string.h>

using namespace std;

int main()
{
  char str_var1[] = "BigFanOfLionelMessi";
  char str_var2[] = "kc";
  char *k;
  k = strpbrk(str_var1, str_var2);
  if (k != 0)
  {
    cout << "Matching character:" << *k;
  }
  else
  {
    cout << "Error! Character not found";
  }
}

Output

Error! Character not found

See also

C++ strcspn()

C++ strcncmp()

C++ strcmp()

C++ strchr()

C++ memchr()

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.