📌 Find Substring Position Using strstr() in C

⬅️ Back

🔎 Find a Substring in a String Using strstr() in C

This tutorial shows how to find the position of a substring within a main string using the strstr() function from <string.h>.


✅ Problem Statement

Input two strings from the user: the main string and the substring to search for. Print the position of the substring’s first occurrence if found; otherwise, show a message saying it was not found.


✅ Method 1: Using a Custom Function

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

int findSubstring(char *mainStr, char *subStr) {
    char *pos = strstr(mainStr, subStr);
    if (pos != NULL) {
        return (int)(pos - mainStr);  // zero-based index
    } else {
        return -1; // substring not found
    }
}

int main() {
    char mainStr[200], subStr[100];
    int index;

    printf("Enter the main string: ");
    fgets(mainStr, sizeof(mainStr), stdin);

    printf("Enter the substring to find: ");
    fgets(subStr, sizeof(subStr), stdin);

    // Remove newline characters if present
    size_t lenMain = strlen(mainStr);
    if (lenMain > 0 && mainStr[lenMain - 1] == '\n') {
        mainStr[lenMain - 1] = '\0';
    }
    size_t lenSub = strlen(subStr);
    if (lenSub > 0 && subStr[lenSub - 1] == '\n') {
        subStr[lenSub - 1] = '\0';
    }

    index = findSubstring(mainStr, subStr);

    if (index != -1) {
        printf("Substring found at position: %d\n", index + 1);
    } else {
        printf("Substring not found in the main string.\n");
    }

    return 0;
}

🛠️ Method 2: Without Function (All in main())

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

int main() {
    char mainStr[200], subStr[100];
    char *pos;

    printf("Enter the main string: ");
    fgets(mainStr, sizeof(mainStr), stdin);

    printf("Enter the substring to find: ");
    fgets(subStr, sizeof(subStr), stdin);

    // Remove newline characters if present
    size_t lenMain = strlen(mainStr);
    if (lenMain > 0 && mainStr[lenMain - 1] == '\n') {
        mainStr[lenMain - 1] = '\0';
    }
    size_t lenSub = strlen(subStr);
    if (lenSub > 0 && subStr[lenSub - 1] == '\n') {
        subStr[lenSub - 1] = '\0';
    }

    pos = strstr(mainStr, subStr);

    if (pos != NULL) {
        printf("Substring found at position: %ld\n", pos - mainStr + 1);
    } else {
        printf("Substring not found in the main string.\n");
    }

    return 0;
}

📌 Summary

The strstr() function returns a pointer to the first occurrence of the substring in the main string or NULL if not found. This example covers both function and inline approaches.

strstr in c, find substring in string c, c program substring search, strstr example c, substring position c programming, string search c, strstr tutorial

āĻ•োāύ āĻŽāύ্āϤāĻŦ্āϝ āύেāχ:

āĻāĻ•āϟি āĻŽāύ্āϤāĻŦ্āϝ āĻĒোāϏ্āϟ āĻ•āϰুāύ