strstr() function takes two strings as arguments and searches the first string for an occurrence of the second string.
char *strstr(const char *str1 , const char *str2 );
Finds the first occurrence of the entire string str2 which appears in the string str1.
Returns a pointer to the first occurrence of str2 in str1.
If no match was found, then a null pointer is returned.
If str2 points to a string of zero length, then the argument str1 is returned.
const char * strstr ( const char * str1, const char * str2 ); char * strstr ( char * str1, const char * str2 );
This function has the following parameter.
A pointer to the first occurrence in str1 of the characters specified in str2, or a null pointer if the sequence is not present in str1.
#include <stdio.h>
#include <string.h>
/*from w w w .ja v a 2 s. c o m*/
int main (){
char str[] ="This is a simple string";
char * pch;
pch = strstr (str,"simple");
strncpy (pch,"sample",6);
puts (str);
return 0;
}
The code above generates the following result.
#include <stdio.h>
#include <string.h>
main() { //w w w .j av a 2 s. co m
char *str1 = "this is a testing xyz";
char *str2 = "ing";
char *str3 = "xyz";
printf("\nstr1 = %s\n", str1);
printf("\nstr2 = %s\n", str2);
printf("\nstr3 = %s\n", str3);
if ( strstr(str1, str2) != NULL )
printf("\nstr2 was found in str1\n");
else
printf("\nstr2 was not found in str1\n");
if ( strstr(str1, str3) != NULL )
printf("\nstr3 was found in str1\n");
else
printf("\nstr3 was not found in str1\n");
}
The code above generates the following result.
#include <string.h>
#include <stdio.h>
/*from w ww . ja va 2s.com*/
void find_str(char const* str, char const* substr) {
char* pos = strstr(str, substr);
if(pos) {
printf("found the string '%s' in '%s' at position: %ld\n", substr, str, pos - str);
} else {
printf("the string '%s' was not found in '%s'\n", substr, str);
}
}
int main(void)
{
char* str = "one two three";
find_str(str, "two");
find_str(str, "");
find_str(str, "java2s.com");
find_str(str, "n");
return 0;
}
The code above generates the following result.