strstr() in C - Source Code Example

In this source code example, we will see how to use the strstr() function in C programming with an example.

strstr() Function Overview

The strstr() function in C is used to search for the first occurrence of a substring within a larger string. It returns a pointer to the beginning of the located substring or NULL if the substring is not found.

Source Code Example

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

int main() {
    char str[] = "Programming in C is fun!";
    char sub1[] = "C is";
    char sub2[] = "Java";

    // Search for the first substring in the main string
    char *substring_location1 = strstr(str, sub1);
    if (substring_location1) {
        printf("Found '%s' starting at position: %ld\n", sub1, substring_location1 - str);
    } else {
        printf("Substring '%s' not found.\n", sub1);
    }

    // Search for the second substring in the main string
    char *substring_location2 = strstr(str, sub2);
    if (substring_location2) {
        printf("Found '%s' starting at position: %ld\n", sub2, substring_location2 - str);
    } else {
        printf("Substring '%s' not found.\n", sub2);
    }

    return 0;
}

Output

Found 'C is' starting at position: 14
Substring 'Java' not found.

Explanation

1. We first include the necessary headers, <stdio.h> and <string.h>.

2. In the main function, we define our main string str and two substrings sub1 and sub2.

3. We then use the strstr() function to locate sub1 in str. If found, the position is printed. Otherwise, a "not found" message is displayed.

4. Similarly, we check for the presence of sub2 in str.

5. In this example, while sub1 is found in str, sub2 isn't, so the program gives output accordingly.


Comments