In this article, you will learn about C string library function strstr( ) with step by step explanation and example.
strstr( )
is the built in standard string manipulation function that is defined under string handling library string.h
.
Therefore it is necessary to include string header file to use standard C string library function strstr( )
.
#include<string.h>
char *strstr( const char *str1, const char *str2 );
where,
str1 = string that needs to be scanned
str2 = small string which characters needs to be located in str1
This function identifies all the characters of small string str2
in the large string str1
.
If all the characters from string str2
are located, a pointer to the string in str1
is returned, otherwise, a NULL pointer is returned.
Use: This function is useful when you want to locate the first occurrence of a small string in a huge text.
[adsense1]
/*Use of C string library function strstr*/
#include<stdio.h>
#include<string.h>
int main()
{
//initializing character pointer
const char *str1 = "Learn C from trytoprogram.com";
const char *str2 = "top";
//displaying both string
printf("str1 = %s\n\n", str1);
printf("str2 = %s\n\n", str2);
printf("Remaining part of str1 after the first"
"occurence of str2 = %s\n", strstr(str1, str2));
return 0;
}//end main
Output
Explanation
In this program, we have searched "top"
in the bigger string "Learn C from trytoprogram.com"
.
strstr( )
returns the pointer to the top in str1
and hence the output as shown in the figure.