This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Program to check the occurrences of a pattern in a text/string | |
* This program checks whether the pattern occur in the string | |
* or not, if yes at what positions and also print the text/string | |
* highlighting the occurrences | |
**/ | |
#include <stdio.h> | |
#include<string.h> | |
void check_substring(char *, char *); | |
int main() | |
{ | |
char str[500], substr[50]; | |
printf("\nEnter any string(Max length = 500 char):"); | |
fgets(str, 500, stdin); | |
printf("\nEnter the pattern to be checked:"); | |
fgets(substr, 50, stdin); | |
printf("\nstring = %s", str); | |
printf("substring to be checked = %s", substr); | |
check_substring(str, substr); | |
return 0; | |
} | |
void check_substring(char *s, char *subs) | |
{ | |
int i, j, k, no_of_occurence = 0; | |
int l1, l2, f, pos; | |
int position[100]; /* Keeps all positions where the | |
substring occurs */ | |
l1 = strlen(s); | |
printf("\n\nlength of string = %d", l1); | |
l2 = strlen(subs); | |
printf("\nlength of substring pattern being checked = %d", l2); | |
k = 0; | |
/* Traversing through the string */ | |
for(i = 0; i < l1; i++) { | |
f = i; | |
pos = i; /* Note the starting position */ | |
for(j = 0; j < l2; j++) { | |
if(s[i] == subs[j]) | |
i++; | |
else { | |
i = f + 1; | |
break; | |
} | |
} | |
i--; | |
/* On finding an occurrence */ | |
if(j >= l2) { | |
/* Place start position in the position array */ | |
position[k++] = pos; | |
no_of_occurence++; | |
} | |
} | |
/* If the pattern occurs in the string/text */ | |
if(no_of_occurence > 0) { | |
printf("\n\nThe substring occurs %d times at", no_of_occurence); | |
/* Print all positions */ | |
for(i = 0; i < k; i++) | |
printf("\nposition %d", position[i]); | |
/* The string/text is printed with all occurrences enclosed | |
between ^ and ^ */ | |
printf("\n\nThe text highlighting the occurrences of the substring\n "); | |
k = 0; | |
for(j = 0; j < l1; j++) { | |
if(j == position[k]) | |
printf("^"); | |
printf("%c", s[j]); | |
if(j == position[k] + l2 - 1) { | |
printf("^"); | |
k++; | |
} | |
} | |
} | |
/* If the pattern does not occur in the string/text */ | |
else | |
printf("\n\nThe substring does not occur in the string\n"); | |
} |
No comments:
Post a Comment