C string library function strpbrk()


In this article, you will learn about C string library function strpbrk() with step by step explanation and explicit example.

C string library function strpbrk()

strpbrk() is the built in standard string manipulation function that is defined under string handling library string.h.

Therefore it is necessary to include string header file to use standard C string library function strpbrk().

#include<string.h>

Function prototype of C string library function strpbrk( )

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

where,

               str1 = string that needs to be scanned

                str2 = string which characters needs to be located in str1

This function locates the first character in the str1 that matches any character from second string str2.

If the character from string str2 matches in string str1 then it returns a pointer to the character in the string str1, otherwise, a NULL pointer is returned.

How strpbrk() works?

c library strpbrk
Now, let’s be clear from example.

Example: Program to demonstrate the use to C string library function strpbrk()

//Use of string manipulation function strpbrk

#include<stdio.h>
#include<string.h>

int main()
{
   //initialization of char type pointer
   const char *str1 = "trytoprogram.com";
   const char *str2 = "hello";
   char *ret; //character type pointer

   printf("str1 = %s\n\nstr2 = %s\n\n", str1, str2);

   //pointer from function is stored in ret
   ret = *strpbrk( str1, str2 );

   printf("'%c' appears first in the string str1 from the string str2.\n", ret);

   return 0;
} //end

Output

c strpbrk output

Explanation

In the above program, we have initialized two char type pointer str1 and str2.

As mentioned in the picture above, 'o' is the first character in the string str1 that matches the character in the string str2.