strstr() in C/C++ (original) (raw)

Last Updated : 5 Jun, 2026

strstr() is a predefined C/C++ string function used to find the first occurrence of one string inside another string. It is declared in the <string.h> (or ) header file.

#include using namespace std;

int main() { char s1[] = "GeeksforGeeks"; char s2[] = "for";

if (strstr(s1, s2))
    cout << "String found";
else
    cout << "String not found";

return 0;

}

`

Syntax

char *strstr (const char *s1, const char *s2);

**Parameters:

The strstr() function takes two strings as arguments to perform substring searching.

**Return Value:

The function returns the position of the first occurrence of the substring in the main string.

The strstr() function is used for locating a substring within a string.

Application****:** Replace a String with Another

In this example with the help of strstr() function we first search for the occurrence of substring "STL" in s1 and after that replace that word with "Strings".

C++ `

#include #include using namespace std; int main() { // Take any two strings char s1[] = "Fun with STL"; char s2[] = "STL"; char* p;

// Find first occurrence of s2 in s1
p = strstr(s1, s2);

// Prints the result
if (p) {
    strcpy(p, "Strings");
    cout << s1;
}
else {
    cout << "String not found" << endl;
}

return 0;

}

C

#include <stdio.h> #include <string.h>

int main() { // Take any two strings char s1[] = "Fun with STL"; char s2[] = "STL"; char* p;

// Find first occurrence of s2 in s1
p = strstr(s1, s2);

// Prints the result
if (p) {
    strcpy(p, "Strings");
    printf("%s", s1);
}
else
    printf("String not found\n");

return 0;

}

`

**Time Complexity: O(n + m), where n is the size of s1 and m is the size of s2.
**Auxiliary Space: O(m), where m is the size of s2.