The library also provides several string searching functions, which are as follows −
| char *strchr (const char *string, intc); | Find first occurrence of character c in string. |
| char "strrchr (const char "string, intc); | Find last occurrence of character c in string. |
| char *strpbrk (const char *s1,const char *s2); | returns a pointer to the first occurrence in string s1 of any character from string s2, or a null pointer if no character from s2 exists in s1. |
| size_t strspn (const char *s1, const char *s2); | returns the number of characters at the beginning of s1 that match s2. |
| size_t strcspn (const char *51, const char *s2); | returns the number of characters at the beginning of s1 that do not match s2. |
| char *strtok (char *s1,const char *s2); | break the string pointed to by si into a sequence of tokens, each of which is delimited by one or more characters from the string pointed to by s2. |
| char *strtok_r (char *s1,const char *s2, char | has the same functionality as strtok () except**lasts); that a pointer to a string placeholder lasts must be supplied by the caller. |
strchr () and strrchr () are the simplest to use.
Example 1
Following is the C program for the string searching functions −
#include <string.h>
#include <stdio.h>
void main(){
char *str1 = "Hello";
char *ans;
ans = strchr (str1,'l');
printf("%s\n", ans);
}Output
When the above program is executed, it produces the following result −
llo
After this execution, ans points to the location str1 + 2.
strpbrk () is a more general function that searches for the first occurrence of any of a group of characters.
Example 2
Following is the C program for the use of strpbrk () function −
#include <string.h>
#include <stdio.h>
void main(){
char *str1 = "Hello";
char *ans;
ans = strpbrk (str1,"aeiou");
printf("%s\n",ans);
}Output
When the above program is executed, it produces the following result −
ello
Here, ans points to the location str1 + 1, the location of the first e.