
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
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;
- Related Articles
- strstr() function in C/C++
- What is strstr() Function in C language?
- strstr() function in PHP
- Implement strStr() in Python
- isless() in C/C++
- islessgreater() in C/C++
- isgreater() in C/C++
- modf() in C/C++
- isblank() in C/C++
- islessequal() in C/C++
- strxfrm() in C/C++
- Comments in C/C++
- isgreaterequal() in C/C++
- ungetc() in C/C++
- (limits.h) in C/C++
