C PROGRAMMING PROGRAM • STRINGS

Find a Substring Without strstr()

Learn how to find a substring without strstr() using a clear C program.

IntermediateStringsPattern matchingNested loops

PROBLEM UNDERSTANDING

Input and expected output

Sample input
CodeBhavya programming
Bhavya
Sample output
Found at position 5

COMPLETE C PROGRAM

Complete C implementation

substring-search.c
Open in compiler
#include <stdio.h>
#include <string.h>

int main(void)
{
    char text[300], pattern[100];
    int position = -1;

    fgets(text, sizeof text, stdin);
    fgets(pattern, sizeof pattern, stdin);
    text[strcspn(text, "\n")] = '\0';
    pattern[strcspn(pattern, "\n")] = '\0';
    for (int start = 0; text[start] != '\0'; start++) {
        int offset = 0;
        while (pattern[offset] != '\0' && text[start + offset] == pattern[offset]) offset++;
        if (pattern[offset] == '\0') { position = start; break; }
    }
    if (position >= 0) printf("Found at position %d\n", position + 1);
    else printf("Substring not found\n");
    return 0;
}

GUIDED CODE TOUR • NOT LIVE EXECUTION

Study the program line by line

Use the real compiler button above to run and debug with different inputs.

CURRENT STEP

Select Start to walk through the important lines.

SELECTED LINE

No line selected

EXPECTED OUTPUT FOR THE SAMPLE

Found at position 5
0%Step 0 of 0

PROGRAM EXPLANATION

Algorithm and explanation

  1. Read the required input values.
  2. Try every possible start position and compare pattern characters until a mismatch or full match.
  3. Display the computed result.

Try every possible start position and compare pattern characters until a mismatch or full match.

EFFICIENCY

Time and space complexity

Time complexity

O(nm)

Auxiliary space

O(1)

DEBUGGING CHECKLIST

Common mistakes

Check this

Use the correct format specifier for every variable.

Check this

Initialize variables before using their values.

Check this

Check braces, semicolons and input order carefully.

Try it yourself

Practice: Run the program with the sample input, predict its output, and then test one boundary case of your own.