C++ strstr() Function Example | strstr() in C++
C++ strstr() is an inbuilt string handling function that is used to find the first occurrence of a substring in a given string. It is defined in string.h header file. It is used to find the occurrence of a substring in a string. This process of matching stops at ‘\0’ and does not include it.
C++ strstr()
The strstr() method in C++ finds the first occurrence of the byte string target in the byte string pointed to by the str. The terminating null characters are not compared.
Syntax
char *strstr( const char *str_var, const char *str_var2)
The function finds the occurrence of str_var2 in str_var1 and stops where it gets the first occurrence. (It doesn’t count the null character).
Parameters
It takes two parameters. The first one, str_var is the main string from which we will search the substring. The second one is the substring (str_var2), which is to be searched in the main string(str_var).
Return Value
It returns a pointer which points to the first character of the substring (str_var2) with the index of main string(str_var) only if the substring is found. If a substring is not found, it returns a null pointer. If the substring is found, then strstr() method returns the pointer to the first character of a substring in dest. If the substring is not found, a null pointer is returned. If the dest points to an empty string, str is returned
Example program on strstr() function in C++
Example 1: Write a program to show the working of strstr() in C++.
#include <iostream> #include <string.h> #include <stdio.h> using namespace std; int main() { char str_var[] = "HelloBOYSandGIRLS"; char str_var2[] = "BOYS"; char *k; k = strstr(str_var, str_var2); if (k) { cout << "Main string: " << str_var << endl; cout << "Substring: " << str_var << endl; cout << "Congo! Substring is present"; } else { cout << "Substring not found"; } return 0; }
Output
Main string: HelloBOYSandGIRLS Substring: BOYS Congo! Substring is present
Example 2: Write a program in which the substring points to an empty string and then print the output.
See the following code.
#include <iostream> #include <string.h> #include <stdio.h> using namespace std; int main() { char str_var[] = "HelloBOYSandGIRLS"; char str_var2[] = " "; char *k; k = strstr(str_var, str_var2); if (k) { cout << k; } else { cout << "Substring not found"; } return 0; }
Output
Substring not found