The strchr()
function is a built-in library function declared in the string.h
header file.
It finds the first occurrence of a character in a string and returns a pointer to the found character, or null pointer, if no such character is found.
strchr()
takes string as a first argument, character as a second, and returns a pointer to char
.
char* strchr(const char* str, int ch);
const char* string = "hello";
strchr(string, 'l'); // returns pointer to the third character of the string
const char* string = "hello";
strchr(string, 'a'); // returns NULL
#include <stdio.h>#include <string.h>int main(){const char *str = "To be, or not to be: that is the question";char target = 't';const char *result = str;// Find the first occurence of the targetresult = strchr(result, target);while (result != NULL) {printf("Found '%c' starting at '%s'\n", target, result);// Increment result, otherwise we'll find target at the same location++result;// Find the next occurence of the targetresult = strchr(result, target);}}