C PROGRAMMING PROGRAM • STRINGS
Find a Substring Without strstr()
Learn how to find a substring without strstr() using a clear C program.
PROBLEM UNDERSTANDING
Input and expected output
Sample input
CodeBhavya programming Bhavya
Sample output
Found at position 5
COMPLETE C PROGRAM
Complete C implementation
#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;
}CURRENT STEP
SELECTED LINE
EXPECTED OUTPUT FOR THE SAMPLE
Found at position 5
Step 0 of 0
PROGRAM EXPLANATION
Algorithm and explanation
- Read the required input values.
- Try every possible start position and compare pattern characters until a mismatch or full match.
- 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.
