![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
strstr() in C++
The strstr() function is a predefined function in string.h. It is used to find the occurance of a substring in a string. This process of matching stops at ‘\0’ and does not include it.
Syntax of strstr() is as follows −
char *strstr( const char *str1, const char *str2)
In the above syntax, strstr() finds the first occurance of string str2 in the string str1. A program that implements strstr() is as follows −
Example
#include <iostream> #include <string.h> using namespace std; int main() { char str1[] = "Apples are red"; char str2[] = "are"; char *ptr; ptr = strstr(str1, str2); if(ptr) cout<<"Occurance of \""<< str2 <<"\" in \""<< str1 <<"\" is at position "<<ptr - str1 + 1; else cout<<"There is no occurance of \""<< str2 <<"\" in "<<str1; return 0; }
Output
The output of the above program is as follows −
Occurance of "are" in "Apples are red" is at position 8
In the above program, str1 and str2 are defined with the values “Apples are red” and “are” respectively. This is given below −
char str1[] = "Apples are red"; char str2[] = "are"; char *ptr;
The pointer ptr points to the first occurrence of “are” in “Apples are red”. This is done using strstr() function. The code snippet for this is given below −
ptr = strstr(str1, str2);
If the pointer ptr contains a value, then the position of str2 in str1 is displayed. Otherwise, it is displayed that there is no occurrence of ptr2 in ptr1. This is shown below −
if(ptr) cout<<"Occurance of \""<< str2 <<"\" in \""<< str1 <<"\" is at position "<<ptr - str1 + 1; else cout<<"There is no occurance of \""<< str2 <<"\" in "<<str1;