C Reference ยท string.h
C strchr() and strrchr() functions
Reference for C strchr() and strrchr(): find the first or last occurrence of a character in a string, the terminator rule, and C23 const-preserving behavior.
strchr() returns a pointer to the first occurrence of a character in a string, or NULL if it is not there. strrchr() does the same for the last occurrence. They are the building blocks for splitting file names at a dot, cutting a line at a newline, or finding a separator.
The result is a pointer into the original string, not a copy. Subtracting the string's start gives the index.
#include <string.h> char *strchr(const char *s, int c); char *strrchr(const char *s, int c);
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.
Syntax
char *strchr(const char *s, int c); char *strrchr(const char *s, int c);
| Name | Description |
|---|---|
s |
The string to search. |
c |
The character to find, converted to char. |
Returns: a pointer to the match, or NULL if the character does not occur. Searching for '\0' returns a pointer to the terminator.
Errors / undefined behavior: s must be a terminated string. NULL is undefined.
Usage notes
- Always test for
NULLbefore using the result. Dereferencing a failed search crashes. - The terminator counts as part of the string.
strchr(s, '\0')finds the end, which is occasionally useful as an alternative tostrlen. - The argument is an
intbut is converted tochar. Pass a character, not a string:strchr(s, "x")is a bug (the compiler warns) because a literal is a pointer. - Const-correctness. In C before C23 the function accepts
const char *and returnschar *, so it can hide aconstviolation. In C23 (and in C++) the return type follows the qualification of the argument when the library supports the generic version, so aconst char *input gives aconst char *result. Do not assume either; assign to a pointer of the matching constness. - Complexity is linear in the length.
strrchrscans the whole string. - To find any of several characters, use
strpbrk. For a substring, usestrstr. - For bytes in memory that may contain zeros, use
memchr. - Splitting: writing
'\0'over the match turns one string into two, but only if the string is a modifiable array and not a literal.
Related
strstr,strpbrk,strspnandstrcspn,strtok,memchr- Lessons: Strings, String functions