Skip to content

Instantly share code, notes, and snippets.

@mbalayil
Created May 15, 2011 12:32
Show Gist options
  • Save mbalayil/973110 to your computer and use it in GitHub Desktop.
Save mbalayil/973110 to your computer and use it in GitHub Desktop.
Check the occurrences of a pattern in a string
/**
* 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");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment