对于短输入有效,对于长输入失败。如何解决?
我有这个程序可以在字符串中查找子字符串。它适用于小输入。但对于长输入会失败。这是程序:
//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
这是完全错误的。有哪位高手可以帮我找到解决办法吗?
PS: 这有点像重新发明轮子,因为 strstr() 具有此功能。但我正在尝试一种非图书馆的方式来做到这一点。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您需要使用
strncmp
而不是strcmp
并将比较长度设置为等于strlen(search)
。或者您可以使用'\0'
终止 temp。You need to use
strncmp
rather thanstrcmp
and set the comparison length equal tostrlen(search)
. Either that or you could just terminate temp with a'\0'
.好吧,首先,在第二种情况下“temp”不会以空终止。这就是为什么你的第一个案例有效;如果你搜索“好”,它就不起作用。
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."
如果您想完全避免 strcmp,那么您已经完成了 99% 的工作。只需在退出比较循环时根据您的标记/搜索字符串长度检查 j ,您就会知道是否有匹配项。
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.