In C++, strchr() searches a C-string for one character and stops at the first match. Write the character in single quotes, such as '@'.
Both arguments are required. If the character is found, you get a pointer to that spot inside the same string. If it is missing, the result is nullptr. Check for that before you use the pointer. Include <cstring>.
Syntax
Pass the string, then the character in single quotes.
C++
strchr("user@mail", '@');
Call
What it does
strchr("user@mail", '@')
Points at the first @ inside the string.
Library declarations
C++
const char* strchr(const char* str, int ch);
Parameters
Parameter
Description
str
Required. The C-string to search.
ch
Required. The character to find, written in single quotes.
Return Value
Return Value
Description
Pointer
Points at the first matching character inside the same string.
nullptr
The character is not in the string.
C++ Examples
Example 1 — Basic strchr()
Find the first 'C' in a greeting.
C++
#include <iostream>
#include <cstring>
int main() {
const char* text = "Hello, C++!";
const char* found = strchr(text, 'C');
if (found != nullptr) {
std::cout << "Found: " << found << '\n';
} else {
std::cout << "Not found.\n";
}
return 0;
}
Output
Found: C++!
How It Works
strchr scans left to right until it sees 'C'.
The returned pointer starts at that character.
Printing the pointer shows the rest of the string from there.