The strchr() function from <cstring> locates the first occurrence of a character in a null-terminated C-string. It returns a pointer to that character—or nullptr if the character is absent—making it essential for parsing emails, paths, and token boundaries in C-style text.
01
Find a Character
Search C-strings.
02
Returns char*
Or nullptr.
03
Get Index
result - str
04
Case-Sensitive
Exact char match.
05
First Match
Leftmost only.
06
vs strrchr()
Last occurrence.
Fundamentals
Definition and Usage
In C++, strchr() is declared in <cstring>. It scans a C-string from left to right until it finds the requested character or reaches the null terminator '\0'. The second parameter is typed as int but is normally a character value such as 'C' or '@'.
When a match is found, the return value points into the original string—you do not get a new copy. Subtracting the base pointer (result - str) yields the zero-based index, a common interview and debugging trick.
💡
Beginner Tip
Always check for nullptr before using the returned pointer or computing an index. If the character is missing, dereferencing the result would crash your program.
Foundation
📝 Syntax
The standard library declaration:
C++
const char* strchr(const char* str, int character);
Parameters
str — pointer to a null-terminated C-string to search.
character — the character to find, passed as int (e.g. 'C', '@', or 67 for ASCII 'C').
Return Value
Pointer to the first matching character in str, or nullptr if not found. Also returns a pointer to the terminating '\0' when searching for '\0'.
Header
#include <cstring>
Cheat Sheet
⚡ Quick Reference
String
Call
Result
"Hello, C++!"
strchr(s, 'C')
pointer at index 7
"Hello, C++!"
strchr(s, 'z')
nullptr
"user@mail.com"
strchr(s, '@')
pointer at index 4
"a.b.c"
strchr(s, '.')
first '.' at index 1
index from pointer
result - s
zero-based position
Basic
strchr(text, 'C')
Find character
Check found
if (p != nullptr)
Before using p
Index
std::ptrdiff_t i = p - text;
Pointer difference
std::string
s.find('C')
Modern alternative
Hands-On
Examples Gallery
Compile with g++ strchr.cpp -std=c++17 -o strchr. Each example shows how to search, test for success, and compute positions safely.
📚 Getting Started
Locate a character and report its position.
Example 1 — Basic strchr() Usage
Search for 'C' in "Hello, C++!". The match starts at index 7.
C++
#include <iostream>
#include <cstring>
int main() {
const char* sentence = "Hello, C++!";
char searchChar = 'C';
const char* result = strchr(sentence, searchChar);
if (result != nullptr) {
std::cout << "Character '" << searchChar
<< "' found at position: "
<< (result - sentence) << std::endl;
} else {
std::cout << "Character not found." << std::endl;
}
return 0;
}
📤 Output:
Character 'C' found at position: 7
How It Works
strchr returns a pointer to the 'C' inside the same memory as sentence. Subtracting sentence from result converts that pointer into a zero-based index.
Example 2 — Character Not Found
When the character is absent, the function returns nullptr—never dereference without checking.
C++
#include <iostream>
#include <cstring>
int main() {
const char* word = "Hello";
const char* found = strchr(word, 'z');
if (found == nullptr) {
std::cout << "'z' is not in the word." << std::endl;
} else {
std::cout << "Found at " << (found - word) << std::endl;
}
return 0;
}
📤 Output:
'z' is not in the word.
How It Works
The scan reaches '\0' without seeing 'z', so strchr returns nullptr. This is the C-string equivalent of std::string::npos.
📈 Practical Patterns
Validation, indexing, and modern C++ equivalents.
Example 3 — Validate an Email-Like String
Check whether an @ symbol appears—a simple first step in format validation.
C++
#include <iostream>
#include <cstring>
int main() {
const char* email = "user@example.com";
const char* at = strchr(email, '@');
if (at != nullptr) {
std::cout << "Valid format hint: @ at index "
<< (at - email) << std::endl;
} else {
std::cout << "Missing @ symbol." << std::endl;
}
return 0;
}
📤 Output:
Valid format hint: @ at index 4
How It Works
strchr finds the first @. Real email validation needs more rules, but this shows how character search locates delimiters quickly.
Example 4 — Slice Text After a Delimiter
Use the returned pointer to read the substring starting at the match (after checking for nullptr).
std::string::find(char) mirrors strchr for a single character but fits object-oriented C++ code. Use strchr when your data is already const char*.
Applications
🚀 Common Use Cases
Delimiter search — locate '@', ':', '/', or '=' before splitting text.
Path parsing — find slash characters in file paths (often paired with loops).
Presence checks — verify a required symbol exists in user input.
Substring start — use the returned pointer as the beginning of a suffix.
C API interop — work with libraries that pass char* strings.
🧠 How strchr() Works
1
You pass str and character
The function receives a C-string pointer and the character code to search for.
Input
2
Scan left to right
Each byte is compared until a match is found or '\\0' ends the string.
Search
3
Match or end of string
On success, return address of matching char. On failure, return nullptr.
Result
=
🔍
Pointer or nullptr
Use the pointer for suffix access, or subtract the base address to get an index.
Important
📝 Notes
Search is case-sensitive—'A' and 'a' differ.
Always test for nullptr before dereferencing or subtracting pointers.
The return pointer points into the original string—it is not a separate allocation.
Searching for '\0' returns a pointer to the terminator at the end of the string.
For the last occurrence, use strrchr() instead.
Performance
⚡ Optimization
strchr() is highly optimized in standard libraries and is appropriate for typical string lengths. For repeated searches on the same data, consider scanning once in a loop (as in Example 4) rather than restarting from the beginning unnecessarily. For heavy text processing, higher-level tools (std::string, string views, or parsers) may be clearer and safer.
Wrap Up
Conclusion
strchr() is the standard way to find a single character in a C-string. Remember the return type is a pointer (or nullptr), compute indexes with pointer subtraction only after a successful match, and prefer std::string::find when you are already using C++ strings.
Practice the examples, then continue to strcmp() for comparing two C-strings lexicographically.
Use std::string::find in modern C++ code when possible
❌ Don’t
Dereference a null return pointer
Subtract pointers when result is nullptr
Pass non-null-terminated buffers as str
Expect case-insensitive matching by default
Confuse strchr (first) with strrchr (last)
Summary
Key Takeaways
Knowledge Unlocked
Five things to remember about strchr()
Use these points whenever you search C-strings for a character.
5
Core concepts
🔍01
Find Character
In C-strings.
Basics
📝02
char* Result
Or nullptr.
Return
🔢03
Get Index
result - str
Pattern
📈04
First Match
Left to right.
Behavior
💬05
Case-Sensitive
Exact match only.
Rule
❓ Frequently Asked Questions
strchr() searches a null-terminated C-string for the first occurrence of a character. It returns a pointer to that character inside the string, or nullptr if the character is not found.
const char* strchr(const char* str, int character); Include <cstring>. The second argument is an int (usually a char value like 'C' or '@'). The string must be a valid null-terminated C-string.
A pointer to the first matching character in str, or nullptr if no match exists. You can compute the zero-based index with result - str when result is not nullptr.
Yes. 'A' and 'a' are different. For case-insensitive search on C-strings, compare lowered characters in a loop or use std::string with custom logic.
strchr() finds the first (leftmost) occurrence. strrchr() finds the last (rightmost) occurrence—useful for file extensions or the final slash in a path.
Use strchr() for C-style char* strings and C APIs. Use std::string::find() for std::string objects—it returns an index (or npos) and fits modern C++ code more naturally.
Did you know?
Pointer subtraction (result - str) is only valid when both pointers point into the same array and result is not null. The result type is std::ptrdiff_t—a signed integer large enough to represent the distance between two pointers.