strstr() function in C++

As it is quite evident from the name that strstr() function in C++ is a function that does some string related tasks. And like most of the built-in string functions, this function is also defined in <string.h> header. In this tutorial, we will be discussing how it works and how we can use it in a program.

C++ strstr() function

First, let us see the syntax of the strstr() function:

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

As you can see in the above syntax, the function takes two parameter strings, s1 and s2. Note that both of these strings are null-terminated string. The function checks for any occurrence of the second string s2 in the first string s1. If it finds such an occurrence, a pointer to the first character of the substring in s1 is returned by the function. Also, note that it returns a pointer to the first character only for the first occurrence of s2 in s1. If no match is found, it returns a null pointer.

The below example code will help you understand its working and application. Have a good look.

#include <iostream>
#include <string.h>

int main()
{
  char * s1 = "112233445566778899";
  char * s2 = "44";
  
  char * ret;
  
  //finding occurrence of s2 in s1
  ret = strstr(s1, s2);
  
  std::cout << ret;
  
  return 0;
}

Output:

445566778899

Explanation:

In the above code, first, we have initialized two strings s1 and s2. The function finds the first occurrence of s2 in s1 at the 6th index and returns a character pointer ret which points to the first character of substring s2 in s1. When we print this pointer using std::cout, the remaining string is printed.

This function can be very useful while dealing with different strings in C++. Hope you understood the concept.

Thank you.

Also read: Some Useful Built-in String Functions in C++

Leave a Reply

Your email address will not be published. Required fields are marked *