strstr() in C

In C++, std::strstr() is a predefined function used for string handling. string.h is the header file required for string functions.

This function takes two strings s1 and s2 as an argument and finds the first occurrence of the sub-string s2 in the string s1. The process of matching does not include the terminating null-characters(‘\0’), but function stops there.

The strstr() function in C is used to search for a substring within a given string. The function returns a pointer to the first occurrence of the substring within the string. If the substring is not found, the function returns NULL.

The syntax of the strstr() function is as follows: 

 

char *strstr(const char *str1, const char *str2);

Here, str1 is the string in which we want to search for the substring str2.

The function searches for the first occurrence of the substring str2 in the string str1. If the substring is found, the function returns a pointer to the beginning of the substring. If the substring is not found, the function returns NULL.

For example: 

 

#include 
#include 

int main() {
   char str1[20] = "Hello, World!";
   char str2[10] = "World";
   char *result;

   result = strstr(str1, str2);

   printf("The substring is: %s\n", result);

   return 0;
}

In this example, the strstr() function is used to search for the substring "World" in the string "Hello, World!". The function returns a pointer to the beginning of the substring "World", which is then printed to the console.

Submit Your Programming Assignment Details