Home > Article > Backend Development > strstr() function in C/C++
The strstr() function is a function predefined in the "string.h" header file and is used to perform string processing. This function is used to find the first occurrence of a substring (e.g. str2) within a main string (e.g. str1).
The syntax of strstr() is as follows:
char *strstr( char *str1, char *str2);
str2 is what we want in The substring searched for in the main string str1
If the substring we are searching for is found in the main string , the function will return the address pointer of the substring; otherwise, when the substring is not in the main string, it will return a null pointer.
Note - The matching process does not include the null character (‘\0’), but stops when it encounters the null character.
Input: str1[] = {“Hello World”} str2[] = {“or”} Output: orld Input: str1[] = {“tutorials point”} str2[] = {“ls”} Output: ls point
Live Demonstration
#include <string.h> #include <stdio.h> int main() { char str1[] = "Tutorials"; char str2[] = "tor"; char* ptr; // Will find first occurrence of str2 in str1 ptr = strstr(str1, str2); if (ptr) { printf("String is found\n"); printf("The occurrence of string '%s' in '%s' is '%s'", str2, str1, ptr); } else printf("String not found\n"); return 0; }
If we run the above code, it will generate the following output-
String is found The occurrence of string 'tor' in 'Tutorials' is 'torials
Now, let us try another application of strstr()
We can also use this function to replace a certain part of the string, for example, if we Want to replace the string str1 after finding the first substring str2.
Input: str1[] = {“Hello India”} str2[] = {“India”} str3[] = {“World”} Output: Hello World
Explanation − Whenever the str2 is found in str1 it will be substituted with the str3
Real time Demo
#include <string.h> #include <stdio.h> int main() { // Take any two strings char str1[] = "Tutorialshub"; char str2[] = "hub"; char str3[] = "point"; char* ptr; // Find first occurrence of st2 in str1 ptr = strstr(str1, str2); // Prints the result if (ptr) { strcpy(ptr, str3); printf("%s\n", str1); } else printf("String not found\n"); return 0; }
If we run the above code it will generate the following output-
Tutorialspoint
The above is the detailed content of strstr() function in C/C++. For more information, please follow other related articles on the PHP Chinese website!