C strstr() method

This function searches for the first occurrence of a substring within a string.

Syntax:


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

Parameters:

  • str1: A pointer to the main string to search within.
  • str2: A pointer to the substring to search for.

Return Value:

  • A pointer to the first occurrence of the substring str2 in str1.
  • if the substring is not found then return NULL.

Example:


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

int main() {
    char str[] = "My World!";
    char substr[] = "World";
    
    char *result = strstr(str, substr);
    if (result != NULL) {
        printf("Substring found: %s\n", result);  // Output: World!
    } else {
        printf("Substring not found.\n");
    }
    
    return 0;
}

Output:

Substring found: World!