Works for Short Input, Fails for Long Input. How to Solve?

Posted by r0ach on Stack Overflow See other posts from Stack Overflow or by r0ach
Published on 2010-04-27T20:37:52Z Indexed on 2010/04/27 20:43 UTC
Read the original article Hit count: 137

Filed under:
|
|
|
|

I've this program which finds substring in a string. It works for small inputs. But fails for long inputs. Here's the program:

//Find Substring in given String
#include <stdio.h>
#include <string.h>
main()
{
  //Variable Initialization
  int i=0,j=0,k=0;
  char sentence[50],temp[50],search[50];

  //Gets Strings
  printf("Enter Sentence: ");
  fgets(sentence,50,stdin);
  printf("Enter Search: ");
  fgets(search,50,stdin);

  //Actual Work Loop
  while(sentence[i]!='\0')
  {
    k=i;j=0;
    while(sentence[k]==search[j])
    {
      temp[j]=sentence[k];
      j++;
      k++;
    }
    if(strcmp(temp,search)==0)
      break;
   i++;
  }

  //Output Printing
  printf("Found string at: %d \n",k-strlen(search));
}

Works for:

Enter Sentence: good evening
Enter Search: evening
Found string at 6

Fails for:

Enter Sentence: dear god please make this work
Enter Search: make
Found string at 25

Which is totally wrong. Can any expert find me a solution?

P.S: This is kinda like reinventing the wheel since strstr() has this functionality. But I'm trying for a non-library way of doing it.

© Stack Overflow or respective owner

Related posts about string

Related posts about c