What is strpbrk() in C?

This function finds the first character in the string s1 that matches any character specified in s2 (It excludes terminating null-characters).

The strpbrk() function in C is a library function that is used to find the first occurrence of any character in a set of characters (i.e., a "substring") within a given string. It takes two arguments: the first argument is a pointer to the string to search, and the second argument is a pointer to the substring (i.e., a set of characters) to search for.

The strpbrk() function scans the input string starting from the beginning until it finds a character that matches any of the characters in the substring. When a match is found, the function returns a pointer to the position of the first matching character in the input string. If no match is found, the function returns a null pointer.

Here is the syntax for the strpbrk() function: 

 

char *strpbrk(const char *str, const char *substr);

Here is an example of using strpbrk() function to find the first occurrence of a substring in a string: 

 

#include 
#include 

int main() {
    char *str = "Hello, world!";
    char *substr = "ow";
    char *result = strpbrk(str, substr);
    if (result != NULL) {
        printf("The substring '%s' was found at position %ld.\n", substr, result - str);
    } else {
        printf("The substring '%s' was not found.\n", substr);
    }
    return 0;
}

In this example, the program searches for the substring "ow" in the string "Hello, world!". The output of the program is "The substring 'ow' was found at position 7." because the first occurrence of the substring is in the eighth position of the input string.

Submit Your Programming Assignment Details