strstr() - String Manipulation Function
How to locate substring in C++?
Explanation
strstr() manipulation function is used to locate a substring by returning a pointer to the first occurence of str2 in str1. If no matches are found it returns a null pointer.
Syntax:
char * strstr ( const char * str1, const char * str2 );
Example :
#include <stdio.h> #include <cstring.h> int main () { char str1[] = "indiandir.net is online directory webiste"; char str2[] = "net"; char * pt; pt=strstr(str1,str2); if( pt== NULL ) { printf( "Could not find the substring '%s'\n", str2 ); } else { printf ("First occurence of '%s' is in the %dth position.\n", str2,pt-str1+1); } return 0; } |
Result :
First occurence of 'net' is in the 11th position.
In the above example, strstr() manipulation function is used to locate the substring by finding first occurrence of "net" in "str1".