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 <cstring>) header file.
- It takes two strings as arguments and searches for the first occurrence of the second string in the first string.
- If the substring is found, it returns a pointer to its first occurrence; otherwise, it returns NULL. The null character ('\0') is not included in the matching process.
#include <iostream>
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;
}
Output
String found
- Time Complexity: O(n × m), where
nis the length ofs1andmis the length ofs2. - Auxiliary Space: O(1), as
strstr()does not use any significant extra memory.
Syntax
char *strstr (const char *s1, const char *s2);
Parameters:
The strstr() function takes two strings as arguments to perform substring searching.
- s1: The main string in which the search is performed.
- s2: The substring that needs to be searched within
s1.
Return Value:
The function returns the position of the first occurrence of the substring in the main string.
- Returns a pointer to the first character of
s2found ins1; otherwise, returnsNULL. - If
s2is an empty string (""), the function returnss1.
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".
#include <cstring>
#include <iostream>
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;
}
#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;
}
Output
Fun with Strings
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.