Popular Tutorials
Start Learning C++Certification Courses
Created with over a decade of experience and thousands of feedback.
Python online compiler
JavaScript online compiler
SQL online compiler
Java online compiler
HTML online compiler
C online compiler
C++ online compiler
C# online compiler
PHP online compiler
Swift online compiler
Kotlin online compiler
TypeScript online compiler
Go online compiler
Rust online compiler
Scala online compiler
Dart online compiler
R online compiler
Ruby online compiler
C++ strstr()
The strstr() function in C++ finds the first occurrence of a substring in a string.
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?