Skip to content
Tutorials Center
My learning

Topics

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.

C
#include <string.h>

char *strchr(const char *s, int c);
char *strrchr(const char *s, int c);

Try it

C Finding and splitting

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.

C The terminator and in-place edits

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

C
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 NULL before 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 to strlen.
  • The argument is an int but is converted to char. 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 returns char *, so it can hide a const violation. In C23 (and in C++) the return type follows the qualification of the argument when the library supports the generic version, so a const char * input gives a const char * result. Do not assume either; assign to a pointer of the matching constness.
  • Complexity is linear in the length. strrchr scans the whole string.
  • To find any of several characters, use strpbrk. For a substring, use strstr.
  • 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.