Home C++ Strings Functions strstr() C++ strstr() Function Definition In C++, strstr() searches a C-string for the first occurrence of another C-string.
Include <cstring>. For std::string, prefer find.
This guide shows the C library helper in a C++ .cpp program with std::cout. Prefer std::string for new text code; keep these APIs for C interop and interviews.
Syntax Pass haystack then needle.
const char* p = std::strstr(hay, "C++"); Call What it does std::strstr(haystack, needle)Pointer to match, or nullptr.
Empty needle typically returns haystack.
Library declarations char* strstr(char* haystack, const char* needle);
const char* strstr(const char* haystack, const char* needle); Parameters Parameter Description haystack Null-terminated text to search. needle Null-terminated text to find.
Return Value Return Value Description pointer or null Start of the first match.
C++ Examples 1. Find word 2. Missing 3. Offset Example 1 — Basic strstr() Find C++ inside a sentence.
#include <cstring>
#include <iostream>
int main() {
const char* hay = "Hello C++ world";
const char* p = std::strstr(hay, "C++");
if (p) {
std::cout << p << '\\n';
}
return 0;
} How It Works strstr finds the substring start. Pointer refers to C++. Printing from there shows the suffix. Example 2 — strstr Null No match returns nullptr.
#include <cstring>
#include <iostream>
int main() {
const char* p = std::strstr("abc", "z");
std::cout << (p ? "yes" : "no") << '\\n';
return 0;
} How It Works Needle is absent. Result is null. We print no. Example 3 — Index via Pointer Compute index from pointer difference.
#include <cstring>
#include <iostream>
int main() {
const char* hay = "banana";
const char* p = std::strstr(hay, "na");
std::cout << (p - hay) << '\\n';
return 0;
} How It Works First na starts at index 2. Pointer subtraction yields the offset. Same idea as string::find. Frequently Asked Questions What does strstr do? Finds the first occurrence of a C-string inside another.
Return if missing? nullptr.
std::string alternative? s.find(sub).
Next: strtok() Keep going through the string functions. Split a C-string into tokens (mutates; not thread-safe).
strtok() tutorial → CODETOFUN NEWS
Stay Ahead in Tech Get the latest IT news, programming updates, and technology trends directly on your phone.
About the author Developer, cloud engineer, and technical writer
I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.
9 people found this page helpful
Helpful Share Copy link Suggestion