The strstr() function searches the given string in the specified main string and returns the pointer to the first occurrence of the given string.
C strstr() function declaration
char *strstr(const char *str, const char *searchString)
str – The string to be searched.
searchString – The string that we need to search in string str
Return value of strstr()
This function returns the pointer to the first occurrence of the given string, which means if we print the return value of this function, it should display the part of the main string, starting from the given string till the end of main string.
Example: strstr() function in C
#include <stdio.h> #include <string.h> int main () { const char str[20] = "Hello, how are you?"; const char searchString[10] = "you"; char *result; /* This function returns the pointer of the first occurrence * of the given string (i.e. searchString) */ result = strstr(str, searchString); printf("The substring starting from the given string: %s", result); return 0; }
Output:
The substring starting from the given string: you?
As you can see that we are searching the string “you” in the string “Hello, how are you?” using the function strstr(). Since the function returned the pointer to the first occurrence of string “you”, the substring of string str starting from “you” has been printed as output.
Leave a Reply