C String strchr() Function

Beginner
⏱️ 9 min read
📚 Updated: Jul 2026
🎯 5 Examples
<string.h>

What You’ll Learn

The strchr() function scans a C-string from left to right and returns a pointer to the first matching character. If the character does not appear, it returns NULL. It is one of the most useful tools for parsing text.

01

First Match

Left to right.

02

char* Result

Or NULL.

03

Index

p - str.

04

Case Sensitive

a ≠ A.

05

string.h

Standard C.

06

vs strrchr

Last match.

Definition and Usage

strchr stands for string character. It walks the string byte by byte until it either finds the requested character or reaches the null terminator. The returned pointer points into the original string—no new memory is allocated.

Because the result is a pointer into str, you can use it to read the rest of the string starting at that character, or compute how far the match is from the start with pointer subtraction.

💡
Beginner Tip

Always check if (p != NULL) before using the pointer. Dereferencing a NULL result from strchr crashes the program.

📝 Syntax

Standard C declaration:

C
char *strchr(const char *str, int c);

Parameters

  • str — null-terminated string to search.
  • c — character to find, passed as int (use 'a' or '\n').

Return Value

  • Pointer to the first occurrence of c in str.
  • NULL if c is not found (except see note on '\0' below).
  • If c is '\0', returns a pointer to the terminating null byte.

Header

  • #include <string.h>

⚡ Quick Reference

StringSearch forResult
"Hello, C Programming!"'C'pointer at index 7
"hello"'H'NULL (case-sensitive)
"user@mail.com"'@'points to "@mail.com"
"path/to/file"'/'first '/' (index 4)
index from pointerp = strchr(s, c)p - s when p != NULL
Find
p = strchr(str, ch);

First match

Found?
if (p != NULL) { ... }

NULL check

Index
(size_t)(p - str)

Position

Last match
strrchr(str, ch)

Right to left

Examples Gallery

Compile with gcc strchr.c -std=c11 -o strchr. Every example includes <string.h>.

📚 Getting Started

Locate a character and compute its index in the string.

Example 1 — Find a Character

Search for 'C' in "Hello, C Programming!".

C
#include <stdio.h>
#include <string.h>

int main(void) {
    const char *sample = "Hello, C Programming!";
    char search = 'C';

    char *result = strchr(sample, search);

    if (result != NULL) {
        printf("Character '%c' found at position: %td\n",
               search, result - sample);
    } else {
        printf("Character '%c' not found.\n", search);
    }

    return 0;
}

How It Works

strchr scans from index 0. The space and comma are skipped until 'C' is found at position 7. Pointer subtraction result - sample gives the index.

Example 2 — Character Not Found

Searching for an uppercase letter in an all-lowercase word returns NULL.

C
#include <stdio.h>
#include <string.h>

int main(void) {
    const char *word = "hello";
    char *p = strchr(word, 'H');

    if (p == NULL) {
        printf("'H' not found (strchr is case-sensitive).\n");
    } else {
        printf("Found at %td\n", p - word);
    }

    return 0;
}

How It Works

strchr compares exact byte values. 'H' (72) does not match 'h' (104), so the function reaches '\0' and returns NULL.

📈 Practical Patterns

Parsing, repeated search, and slicing from a match.

Example 3 — Find @ in an Email

Use the returned pointer to inspect the domain part.

C
#include <stdio.h>
#include <string.h>

int main(void) {
    const char *email = "alex@codetofun.com";
    char *at = strchr(email, '@');

    if (at != NULL) {
        printf("Username: %.*s\n", (int)(at - email), email);
        printf("Domain:   %s\n", at + 1);
    } else {
        printf("Invalid email format.\n");
    }

    return 0;
}

How It Works

at points to the '@' character. Bytes before at form the username; at + 1 skips the '@' and points at the domain.

Example 4 — Find Every Occurrence

Call strchr repeatedly on the remainder to list all matches.

C
#include <stdio.h>
#include <string.h>

int main(void) {
    const char *text = "banana";
    const char *cursor = text;
    char *found;

    printf("Positions of 'a': ");
    while ((found = strchr(cursor, 'a')) != NULL) {
        printf("%td ", found - text);
        cursor = found + 1;
    }
    printf("\n");

    return 0;
}

How It Works

After each match, move cursor one byte past the found character so the next search does not stop at the same position. For the last occurrence only, use strrchr instead.

Example 5 — Print From the Match Onward

The return value is a pointer into the original string—use it as a substring.

C
#include <stdio.h>
#include <string.h>

int main(void) {
    const char *path = "C:\\Users\\Docs\\readme.txt";
    char *slash = strchr(path, '\\');

    while (slash != NULL) {
        printf("Segment starts at: %s\n", slash + 1);
        slash = strchr(slash + 1, '\\');
    }

    return 0;
}

How It Works

Each call finds the next backslash. Printing slash + 1 shows the remainder after that separator. On Unix paths, search for '/' the same way.

🚀 Common Use Cases

  • Parse key=value — locate '=' to split configuration lines.
  • Validate email — check for a single '@' separator.
  • Path handling — find directory separators before extracting filenames.
  • CSV rows — find commas between fields.
  • Skip whitespace — find the first non-space character in input.

🧠 How strchr() Works

1

Start at str[0]

Read the string from the beginning.

Scan
2

Compare each byte to c

Stop when bytes match or at '\0'.

Compare
3

Return pointer or NULL

Match → address inside str; no match → NULL.

Result
=

char* match

Use for index, suffix, or looped searches.

📝 Notes

  • Include <string.h>—the old reference example omitted this header.
  • Case-sensitive: use tolower on both sides if you need case-insensitive search.
  • Searching for '\0' returns a pointer to the string end.
  • Do not modify string literals through the returned pointer if str is read-only.
  • For raw memory (not C-strings), use memchr() with an explicit length.

⚡ Optimization

Standard library strchr is highly optimized on most platforms. Avoid writing your own scan loop unless you need special behavior. When searching repeatedly in a loop, advance the start pointer past each match instead of rescanning from index 0.

Conclusion

strchr() finds the first occurrence of a character and returns a pointer into the original string. Check for NULL, use pointer subtraction for indexes, and reach for strrchr() when you need the last match.

Continue with strrchr() to search from the right end of a string.

💡 Best Practices

✅ Do

  • Include <string.h>
  • Check p != NULL before using the result
  • Use %td or cast for printing index from pointer subtraction
  • Advance past matches when searching for all occurrences
  • Use strrchr for the final separator in a path

❌ Don’t

  • Dereference NULL when the character is missing
  • Assume case-insensitive behavior
  • Forget that the pointer aliases the original string
  • Use strchr on non-null-terminated buffers
  • Confuse first match (strchr) with last match (strrchr)

Key Takeaways

Knowledge Unlocked

Five things to remember about strchr()

Use these points when searching strings in C.

5
Core concepts
📝 02

NULL Safe

Check result.

Safety
🔢 03

Index

p - str.

Pointer
📈 04

Parse Text

@, =, /.

Use case
💬 05

vs strrchr

Last match.

Compare

❓ Frequently Asked Questions

strchr() searches a null-terminated string for the first occurrence of a character. It returns a pointer to that character inside the string, or NULL if the character is not found.
char* strchr(const char* str, int c); Include <string.h>. str is the string to search. c is the character to find, passed as int (often a char literal like 'a').
It returns NULL. Always check the result before dereferencing or using pointer arithmetic.
If char* p = strchr(str, c) is not NULL, the zero-based index is p - str (pointer subtraction). Print it portably with printf("%td", p - str) or cast to size_t.
Yes. 'C' and 'c' are different characters. For case-insensitive search, compare with tolower()/toupper() in a loop or use platform-specific helpers.
strchr() finds the first occurrence of a character scanning left to right. strrchr() finds the last occurrence scanning from the end. Use strchr for the first match; strrchr for the final one (e.g., last '/' in a path).
Did you know?

POSIX also provides strchrnul(), which returns a pointer to the terminating '\0' instead of NULL when the character is not found—that avoids a separate null check in some loops. It is not part of standard C, but GNU libc supports it.

Continue the String Functions Series

Find the first character with strchr(), then learn reverse search with strrchr().

Next: strrchr() →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

6 people found this page helpful