适用于短输入,长输入失败。怎么解决?

问题描述:

我有这个程序,它发现字符串中的子字符串。它适用于小投入。但对于长时间输入而言失败这里的程序:适用于短输入,长输入失败。怎么解决?

//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)); 
} 

作品为:

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

失败了:

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

这是完全错误的。任何专家都可以找到我的解决方案?

P.S:由于strstr()具有此功能,所以这有点像重新发明*。但我正在试图以非图书馆的方式来做到这一点。

+0

呃。 Fortran77已经死了。你可以请使用更好的变量名称。你让我的头受伤:) – 2010-04-27 20:42:11

+0

@Michael Dorgan:我承认最​​近去年在FORTRAN 77专业编程。但是,我认为i,j,k是完全合法的循环控制变量。较短的可视范围证明了短变量名称IMO的作用。 – 2010-04-27 20:45:14

+0

我对我没有问题。我不会在j打一个睫毛。我,jk,正在推动它 - 特别是在循环上下文环境中,事情开始变得混乱。 – 2010-04-27 20:47:02

您需要使用strncmp而不是strcmp,并将比较长度设置为strlen(search)。无论是或者你可以用'\0'来终止温度。

那么,首先,“temp”在第二种情况下不会被终止。这就是为什么你的第一个案件有效;如果你搜索“好”,它将无法工作。

+0

好抓!这可能已经钉牢了。 – 2010-04-27 20:50:59

如果你想完全避免strcmp,你已经完成了99%的工作。在比较循环退出时,只需检查j对抗令牌/搜索字符串的长度,就会知道是否有匹配。