Program 7 : String Matching
Develop a program to perform String Matching using Brute Force Method.
Brute Force String Matching
c
#include <stdio.h>
#include <string.h>
int bruteForceMatch(char text[], char pattern[]) {
int n = strlen(text);
int m = strlen(pattern);
for (int i = 0; i <= n - m; i++) {
int j;
for (j = 0; j < m; j++) {
if (text[i + j] != pattern[j])
break;
}
if (j == m)
return i;
// Match found at index i
}
return -1;
// No match found
}
int main() {
char text[1000], pattern[100];
printf("Enter the text: ");
fgets(text, sizeof(text), stdin);
text[strcspn(text, "\n")] = '\0'; // Remove newline
printf("Enter the pattern: ");
fgets(pattern, sizeof(pattern), stdin);
pattern[strcspn(pattern, "\n")] = '\0'; // Remove newline
int position = bruteForceMatch(text, pattern);
if (position != -1)
printf("Pattern found at position %d\n", position);
else
printf("Pattern not found in the text.\n");
return 0;
}
It loops over every possible starting position
i
in the text (from0
ton - m
).For each position, it checks if the substring of length
m
starting ati
matches the pattern.If it matches, it returns the starting index
i
.If no match is found, it returns
-1
.
Reading Input with fgets()
c
printf("Enter the text: ");
fgets(text, sizeof(text), stdin);
text[strcspn(text, "\n")] = '\0'; // Remove newline
scanf("%s", text)
stops at spaces —fgets
is better for reading full sentences.
fgets(text, sizeof(text), stdin);
Reads a full line of input (including spaces) from the user and stores it in the
text
array.sizeof(text)
ensures you don’t read beyond the array size.
text[strcspn(text, "\n")] = '\0';
fgets()
includes the newline character (\n
) when the user presses Enter.strcspn(text, "\n")
finds the index of the newline.This line replaces
\n
with\0
, effectively removing the newline from the input string.