C programming string.h function - char *strstr(const char *haystack, const char *needle)

‮.www‬theitroad.com

The strstr function in the C programming language is declared in the string.h header file. It is used to search for the first occurrence of a substring (needle) within a string (haystack).

The function has the following syntax:

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

where haystack is the string to be searched, and needle is the substring to be found.

The function returns a pointer to the first occurrence of needle within haystack, or NULL if needle is not found.

Example usage:

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

int main() {
    char haystack[] = "The quick brown fox jumps over the lazy dog";
    char needle[] = "brown";

    char *result = strstr(haystack, needle);
    if (result == NULL) {
        printf("Substring not found\n");
    } else {
        printf("Substring found at position %ld\n", result - haystack);
    }

    return 0;
}

Output:

Substring found at position 10