strstr() Function

The strstr() function in C locates the first occurrence of a substring within a larger string and returns a pointer to that position if found, or a null pointer if the substring is not present. It performs a search that stops when the terminating null-character of the main string is encountered.


Syntax of strstr()

</>
Copy
const char *strstr(const char *str1, const char *str2);

Parameters

ParameterDescription
str1C string to be scanned.
str2C string containing the sequence of characters to match.

Return Value

Returns a pointer to the first occurrence of the entire sequence specified in str2 within str1, or a null pointer if the sequence is not present.

Note: The search process stops at the terminating null-character of the main string, meaning that the null terminator is not considered part of the matching sequence.


Examples for strstr()

Example 1: Substring Found

This example demonstrates how to use strstr() to locate a substring that exists within a larger string.

Program

</>
Copy
#include <stdio.h>
#include <string.h>

int main() {
    const char *haystack = "Hello, welcome to the world of C programming.";
    const char *needle = "welcome";
    const char *result = strstr(haystack, needle);
    
    if (result != NULL) {
        printf("Substring found: %s\n", result);
    } else {
        printf("Substring not found.\n");
    }
    
    return 0;
}

Output:

Substring found: welcome to the world of C programming.

Example 2: Substring Not Found

This example shows the behavior of strstr() when the substring is absent from the main string.

Program

</>
Copy
#include <stdio.h>
#include <string.h>

int main() {
    const char *haystack = "Learning C string functions.";
    const char *needle = "Python";
    const char *result = strstr(haystack, needle);
    
    if (result != NULL) {
        printf("Substring found: %s\n", result);
    } else {
        printf("Substring not found.\n");
    }
    
    return 0;
}

Output:

Substring not found.