strchr
- C course
- Beginner
- Lesson 88/116
- 5 min
Learn to search for a character in a string with strchr.
strchr: searching for a character
The strchr function finds the first occurrence of a specific character in a string. It comes with the <string.h> header. Its signature is char *strchr(const char *s, int c).
char *p = strchr("merhaba", 'a');
// p points at the first 'a'If it cannot find the character, it returns NULL. Because the return value is a pointer, you compute the index by subtracting p - s. This gives the position from the start.
Computing the index from a pointer
strchr returns a pointer, not an index. To find the index, you subtract the start of the string.
char text[] = "merhaba";
char *p = strchr(text, 'a');
long index = p - text;
// index = 4Here p holds the address of the first 'a'; text is the start of the array. The difference of two pointers gives the number of elements between them. This tells you the position. Always check whether p is NULL first.
Practice Print the index of the first 'a'
Use strchr to find the first 'a' in "merhaba dunya" and print its index with printf. You must include the <string.h> header to use strchr.
Starter code
#include <stdio.h>
int main(void) {
char text[] = "merhaba dunya";
/* Find the first 'a' position with strchr and print it */
return 0;
}Sample solution
#include <string.h>
char *p = strchr(text, 'a');
if (p != NULL) {
printf("%ld\n", (long)(p - text));
}Expected output
4
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does strchr return if the character is not found?
- NULL Correct answer
- An empty string
- 0
- -1
Explanation: strchr returns NULL when nothing is found; it means an invalid pointer.
2 Fill in the blank: strchr call
char *p = ____(text, 'a');
char *p = strchr(text, 'a');
Explanation: strchr searches for a character.
3 Match call to behavior
| Term | Meaning |
|---|---|
strchr(s, c) |
First c position |
p - s |
Index value |
NULL |
Not found |
char * |
Pointer type |