The Wayback Machine - https://web.archive.org/web/20230530212210/https://www.geeksforgeeks.org/strstr-in-ccpp/
Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App
geeksforgeeks
Browser
Continue

Related Articles

strstr() in C/C++

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

In C++, std::strstr() is a predefined function used for string handling. string.h is the header file required for string functions. This function takes two strings s1 and s2 as an argument and finds the first occurrence of the sub-string s2 in the string s1. The process of matching does not include the terminating null-characters(‘\0’), but function stops there. 

Syntax:

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

Parameters:
s1: This is the main string to be examined.
s2: This is the sub-string to be searched in s1 string.

Return Value: This function returns a pointer points to the first character of the found s2 in s1 otherwise a null pointer if s2 is not present in s1. If s2 points to an empty string, s1 is returned. Example: 

C++




// CPP program to illustrate strstr()
#include <string.h>
#include <stdio.h>
 
int main()
{
    // Take any two strings
    char s1[] = "GeeksforGeeks";
    char s2[] = "for";
    char* p;
 
    // Find first occurrence of s2 in s1
    p = strstr(s1, s2);
 
    // Prints the result
    if (p) {
        printf("String found\n");
        printf("First occurrence of string '%s' in '%s' is '%s'", s2, s1, p);
    } else
        printf("String not found\n");
 
    return 0;
}

Output

String found
First occurrence of string 'for' in 'GeeksforGeeks' is 'forGeeks'

Time Complexity: O(n)
Auxiliary Space: O(n)

Application: Replace a string with another In this example with the help of strstr() function we first searches for the occurrence of STL sub-string in s1 and after that replaces that word with Strings. 

CPP




// CPP program to illustrate strstr()
#include <string.h>
#include <stdio.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)
Auxiliary Space: O(n)

This article is contributed by Akash Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.


My Personal Notes arrow_drop_up
Last Updated : 02 Feb, 2023
Like Article
Save Article