Pattern Matching


Alice is given an assignment by her programming teacher. The assignment is to write a program for string matching. \n\nShe was asked to write a function match(char[],char[]) which return an integer. This integer has to be -1 if the match doesn’t occur and the location if the string is present. \n\nFor example the string \”Paris\” is present in \”Welcome to Paris\”. If the string is present then it’s location (i.e. at which position it is present) is printed. We are implementing naive string search algorithm in our program.


#include <stdio.h>
#include <string.h>
int match(char [], char []);
int main() {
  char a[100], b[100];
  int position;
  scanf("%[^\n]s", a);
  scanf(" %[^\n]s", b);
  position = match(a, b);
  if(position != -1) {
    printf("Found at location %d\n", position + 1);
  else {
    printf("Not found.\n");
  return 0;
int match(char text[], char pattern[]) {
  int c, d, e, text_length, pattern_length, position = -1;
  text_length    = strlen(text);
  pattern_length = strlen(pattern);
  if (pattern_length > text_length) {
    return -1;
  for (c = 0; c <= text_length - pattern_length; c++) {
    position = e = c;
    for (d = 0; d < pattern_length; d++) {
      if (pattern[d] == text[e]) {
      else {
    if (d == pattern_length) {
      return position;
  return -1;
Ads Blocker Image Powered by Code Help Pro

Ads Blocker Detected!!!

We have detected that you are using extensions to block ads. Please support us by disabling these ads blocker.