What is strchr in C?

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.

Syntax

strchr() takes string as a first argument, character as a second, and returns a pointer to char.

char* strchr(const char* str, int ch);

Cases

Case 1

const char* string = "hello";
strchr(string, 'l'); // returns pointer to the third character of the string
1 of 3

Case 2

const char* string = "hello";
strchr(string, 'a'); // returns NULL
1 of 6

Code

#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 target
result = 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 target
result = strchr(result, target);
}
}