C++ strstr() Function

Beginner
5 min read
Updated: Nov 2026
3 examples
<cstring>

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.

C++
const char* p = std::strstr(hay, "C++");
CallWhat it does
std::strstr(haystack, needle)Pointer to match, or nullptr.

Empty needle typically returns haystack.

Library declarations
C++
char* strstr(char* haystack, const char* needle);
const char* strstr(const char* haystack, const char* needle);

Parameters

ParameterDescription
haystackNull-terminated text to search.
needleNull-terminated text to find.

Return Value

Return ValueDescription
pointer or nullStart of the first match.

C++ Examples

Example 1 — Basic strstr()

Find C++ inside a sentence.

C++
#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

  1. strstr finds the substring start.
  2. Pointer refers to C++.
  3. Printing from there shows the suffix.

Example 2 — strstr Null

No match returns nullptr.

C++
#include <cstring>
#include <iostream>

int main() {
    const char* p = std::strstr("abc", "z");
    std::cout << (p ? "yes" : "no") << '\\n';
    return 0;
}

How It Works

  1. Needle is absent.
  2. Result is null.
  3. We print no.

Example 3 — Index via Pointer

Compute index from pointer difference.

C++
#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

  1. First na starts at index 2.
  2. Pointer subtraction yields the offset.
  3. Same idea as string::find.

Frequently Asked Questions

Finds the first occurrence of a C-string inside another.
nullptr.
<cstring>.
s.find(sub).
Yes.

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.

Your daily dose of tech, straight to your feed.

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.

9 people found this page helpful