Ex.
No: 01
Date: STRING MATCHING
AIM:
To write a C program to find and print all occurrences of a given
pattern pat[] in a text txt[].
ALGORITHM:
• Get the lengths of the pattern (m) and the text (n).
• Use a loop to check every possible starting position of the
pattern in the text.
• For each starting position, use another loop to check if the
substring of the text matches the pattern.
• If a match is found, print the starting index of the match.
CODING:
#include<stdio.h>
#include<conio.h>
#include<string.h>
void stringMatching(char text[],char pattern[]){
int textLength = strlen(text);
int patternLength = strlen(pattern);
int i,j;
for(i=0;i<=textLength-patternLength;i++){
for(j=0;j<patternLength;j++){
if(text[i+j] != pattern[j]){
break;
}
}
if(j == patternLength){
printf("Pattern found at index %d\n",i);
}
}
}
int main(){
char text[100],pattern[50];
clrscr();
printf("Enter the text: ");
gets(text);
printf("Enter the pattern: ");
gets(pattern);
stringMatching(text,pattern);
getch();
return 0;
}
OUTPUT:
RESULT:
Thus, the function is to find and print all occurrences of a
given pattern pat[] in a text txt[] was executed successfully.
Signature of the Faculty