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


i've program finds substring in string. works small inputs. fails long inputs. here's 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: evening enter search: evening found string @ 6 

fails for:

enter sentence: dear god please make work enter search: make found string @ 25 

which totally wrong. can expert find me solution?

p.s: kinda reinventing wheel since strstr() has functionality. i'm trying non-library way of doing it.

you need use strncmp rather strcmp , set comparison length equal strlen(search). either or terminate temp '\0'.


Comments

Popular posts from this blog

javascript - Enclosure Memory Copies -

php - Replacing tags in braces, even nested tags, with regex -