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(sear开发者_Python百科ch));
}
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.
You need to use strncmp
rather than strcmp
and set the comparison length equal to strlen(search)
. Either that or you could just terminate temp with a '\0'
.
Well, to start with, "temp" won't be null terminated in the second case. That's why your first case works; it wouldn't work if you'd searched for "good."
If you wanted to avoid the strcmp completely, you are already doing 99% of its work. Just check j against your token/search string length upon exit of your compare loop and you'll know if you have a match.
精彩评论