C++ strstr()

strstr() prototype

const char* strstr( const char* str, const char* target );
char* strstr( char* str, const char* target );

The strstr() function takes two arguments: str and target. It searches for the first occurrence of target in the string pointed to by str. The terminating null characters are ignored.

It is defined in <cstring> header file.

strstr() Parameters

  • str: Pointer to the null terminated byte string to be searched for.
  • target: Pointer to the null terminated byte string to search for.

strstr() Return value

  • If the substring is found, the strstr() function returns the pointer to the first character of the substring in dest.
  • If the substring is not found, a null pointer is returned.
  • If dest points to an empty string, str is returned

Example: How strstr() function works

#include <cstring>
#include <iostream>

using namespace std;

int main()
{
    char str[] = "Use your brain and heart";
    char target[] = "brain";
    char *p = strstr(str, target);
    
    if (p)
        cout << "'" << target << "' is present in \"" << str << "\" at position " << p-str;
    else
        cout << target << " is not present \"" << str << "\"";

    return 0;
}

When you run the program, the output will be:

'brain' is present in "Use your brain and heart" at position 9
Did you find this article helpful?