C strstr() Function

The strstr() function in C is used to find the first occurrence of a substring in a string. It returns a pointer to the first occurrence of the substring in the string. If the substring is not found, it returns NULL.

Syntax of strstr()

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

Syntax:

                        
char *strstr(const char *haystack, const char *needle);
                        
                    

The function takes two arguments:

The function returns a pointer to the first occurrence of the substring (needle) within the string (haystack). If the substring is not found, it returns NULL.

Example of strstr() Function

Here is an example demonstrating how the strstr() function works. The function will search for a substring within a string and return the location of its first occurrence.

Example:

                        
#include <stdio.h>>
#include <string.h> 
 // For strstr function
        
int main() 
{
    const char *str = "Hello, world! Welcome to C programming.";
    const char *subStr = "world";
        
    // Find the first occurrence of 'world' in the string
    char *result = strstr(str, subStr);
        
    if (result) {
        printf("Substring '%s' found at position: %ld\n", subStr, result - str);
        } else {
            printf("Substring '%s' not found.\n", subStr);
        }
        
        return 0;
}
                        
                    

Output:

Substring 'world' found at position: 7

Explanation of the Example

In this example:

Important Notes