C <string.h> - strchr() Function
The C <string.h> strchr() function is used to find the first occurrence of character in the byte string pointed to by str. The terminating null character is considered as a part of the string and can be found if searching for '\0'.
The function returns pointer to the first occurrence of character in str, or null pointer if character is not found in str.
Syntax
const char * strchr ( const char * str, int character ); char * strchr ( char * str, int character );
Parameters
str |
Specify pointer to the null-terminated byte string to be searched in. |
character |
Specify the character to searched for. |
Return Value
Returns pointer to the first occurrence of character in str, or null pointer if character is not found in str.
Example:
The example below shows the usage of strchr() function.
#include <stdio.h> #include <string.h> int main (){ char MyStr[100] = "To be, or not to be, that is the question."; char * search; //searching for all occurrences of 'o' in MyStr printf("Searching for all occurrences of 'o' in MyStr.\n"); search = strchr(MyStr, 'o'); //displaying the result while(search != NULL) { printf("Found at: %ld\n", (search-MyStr+1)); search = strchr(search+1, 'o'); } return 0; }
The output of the above code will be:
Searching for all occurrences of 'o' in MyStr. Found at: 2 Found at: 8 Found at: 12 Found at: 16 Found at: 40
❮ C <string.h> Library