Library Function strstr() in C++

C++ Library Function : strstr()

On this page we will discuss about library function strstr() in string class which is used in C++. The cstring header file is a C++ header file that provides functions for manipulating C-style strings. strstr() is a function in the C++ standard library that searches for the first occurrence of a substring within a string.

library function strstr() in C++

Library Function strstr() in C++

In C++ programming language, the strstr function is included in cstring header file.

This function takes two arguments: str1 and str2. It searches for the first occurrence of a str2 within str1 and stops on ‘\0′(null terminating character).

Declaration

char *strstr(const char *str1, const char *str2);

Parameters

The strstr function in C++ takes two parameters:

Parameter           Description
str1This is the string in which to search for the substring. It is a pointer to a null-terminated string.
str2This is the string to search for within str1. It is also a pointer to a null-terminated string.

Return value

  • If str2 is found within str1, a pointer to the first occurrence of str2 within str1 is returned.
  • If str2 is not found within str1, a null pointer is returned.
  • If an empty string is found in str2 then str1 is returned.

Implementation of Library Function strstr() :

Example 1:

The following code shows the use of strstr() function.

Run
#include<iostream> 
#include<cstring> 
using namespace std;
int main()
{
    char str1[] = "PrepInsta Prime";
    char str2[] = "Prime";

    char *p = strstr(str1, str2);

    if (p)
    cout << " Found " << str2 << " in " << str1 << " at index " << p-str1;
    else
    cout << str2 << " Did not find " << str1 << " in ";

    return 0;
}

Output:

 Found Prime in PrepInsta Prime at index 10

Example 2:

The following code shows the use of strstr() function when str2 is an empty string.

Run
#include <iostream>
#include <cstring>
using namespace std;

int main()
{
    char str1[] = "PrepInsta Prime";
    char str2[] = "";
    
    char *p = strstr(str1, str2);
    
    if (p)
        cout << " Found " << str2 << " in " << str1 << " at index " << p-str1;
    else
        cout << str2 << " Did not find " << str1 << " in ";

    return 0;
}

Output:

 Found in PrepInsta Prime at index 0

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription