strpbrk() Function
The strpbrk()
function in C searches a string for the first occurrence of any character from a specified set. It traverses the target string and stops as soon as it finds a match, returning a pointer to that location, or a null pointer if no match is found.
Syntax of strpbrk()
char *strpbrk(const char *str1, const char *str2);
Parameters
Parameter | Description |
---|---|
str1 | The string to be scanned for any of the characters. |
str2 | The string containing the set of characters to match. |
The function examines each character in the first string until it finds any character that exists in the second string. The search stops at the first match and does not include the terminating null-characters in either string.
Return Value
The function returns a pointer to the first occurrence in str1
of any of the characters from str2
. If none of the characters are found, it returns a null pointer.
Examples for strpbrk()
Example 1: Finding the First Vowel
This example demonstrates how to use strpbrk()
to locate the first vowel in a string.
Program
#include <stdio.h>
#include <string.h>
int main() {
char text[] = "Hello, World!";
char vowels[] = "aeiouAEIOU";
char *result = strpbrk(text, vowels);
if (result != NULL)
printf("First vowel found: %c\n", *result);
else
printf("No vowel found.\n");
return 0;
}
Output:
First vowel found: e
Example 2: No Matching Characters
This example shows the case where none of the characters from the specified set are found in the string, resulting in a null pointer.
Program
#include <stdio.h>
#include <string.h>
int main() {
char text[] = "Hello, World!";
char digits[] = "0123456789";
char *result = strpbrk(text, digits);
if (result != NULL)
printf("Digit found: %c\n", *result);
else
printf("No digit found.\n");
return 0;
}
Output:
No digit found.
Example 3: Locating a Special Character
This example demonstrates the use of strpbrk()
to find the first occurrence of a special character in a string.
Program
#include <stdio.h>
#include <string.h>
int main() {
char text[] = "Welcome to #CProgramming!";
char specials[] = "#@!$";
char *result = strpbrk(text, specials);
if (result != NULL)
printf("Special character found: %c\n", *result);
else
printf("No special character found.\n");
return 0;
}
Output:
Special character found: #