C library - strpbrk() function



The C library strpbrk() function finds the first character in the string str1 that matches any character specified in str2. This does not include the terminating null-characters. For instance, when user are using csv files, it helps to locate comma, semicolon, or other which separate values.

Syntax

Following is the syntax of the C library strpbrk() function −

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

Parameters

This function accepts the following parameters −

  • str1 − This is the C string to be scanned.
  • str2 − This is the C string containing the characters to match.

Return Value

This function returns a pointer to the character in str1 that matches one of the characters in str2, or NULL if no such character is found.

Example 1

Following is a basic C library program that demonstrates the usage of the strpbrk() function.

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

int main () {
   const char str1[] = "abcde2fghi3jk4l";
   const char str2[] = "34";
   char *ret;

   ret = strpbrk(str1, str2);
   if(ret) {
      printf("First matching character: %c\n", *ret);
   }   
   return(0);
}

Output

On execution of above code, we get the following result −

First matching character: 3

Example 2

In this example, we will find the first occurrence of a character from a set in a string.

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

int main() {
   char str[] = "Hello, World!";
   // Set of characters to search for
   char set[] = "oW"; 

   char *result = strpbrk(str, set);

   if (result != NULL) {
       printf("First occurrence found at index: %ld\n", result - str);
   } else {
       printf("No occurrence found.\n");
   }

   return 0;
}

Output

After executing the code, we get the following result −

First occurrence found at index: 4

Example 3

We create a C program to replace all occurrences of characters from a set in a string.

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

int main() {
   char str[] = "Our Tutorials";
   // Set of characters to search for

   char set[] = "rT"; 
   char *result = strpbrk(str, set);

   if (result != NULL) {
    printf("First occurrence found at index: %ld\n", result - str);
    } else {
    printf("No occurrence found.\n");
    }
   return 0;
}

Output

The above code produces the following result −

First occurrence found at index: 2
Advertisements