This is a C Program to perform string matching without using any specific library functions. A text and a pattern is given as input. The pattern is searched for in the text and all instances of the pattern are given as output.
Here is source code of the C Program to Implement the String Search Algorithm for Short Text Sizes. The C program is successfully compiled and run on a Linux system. The program output is also shown below.
#include<stdio.h>
#include<string.h>
int main() {
char org[100], dup[100];
int i, j, k = 0, len_org, len_dup;
printf("NOTE:Strings are accepted only till blank space.");
printf("\nEnter Original String:");
fflush(stdin);
scanf("%s", &org);
fflush(stdin);
printf("Enter Pattern to Search:");
scanf("%s", &dup);
len_org = strlen(org);
len_dup = strlen(dup);
for (i = 0; i <= (len_org - len_dup); i++) {
for (j = 0; j < len_dup; j++) {
//cout<<"comparing '"<<org[i + j]<<"' and '"<<dup[j]<<"'.";
if (org[i + j] != dup[j])
break;
}
if (j == len_dup) {
k++;
printf("\nPattern Found at Position: %d", i);
}
}
if (k == 0)
printf("\nError:No Match Found!");
else
printf("\nTotal Instances Found = %d", k);
return 0;
}
Output:
$ gcc StringSearch.c $ ./a.out NOTE:Strings are accepted only till blank space. Enter Original String: Stringsareacceptedonlytillblankspace. Enter Pattern to Search: till Pattern Found at Position: 22 Total Instances Found = 1
Sanfoundry Global Education & Learning Series – 1000 C Programs.
advertisement
advertisement
Here’s the list of Best Books in C Programming, Data Structures and Algorithms.
Related Posts:
- Watch Advanced C Programming Videos
- Apply for Computer Science Internship
- Check C Books
- Check Computer Science Books
- Practice Computer Science MCQs