gpt4 book ai didi

c - 在字符串中查找字符串

转载 作者:行者123 更新时间:2023-11-30 18:43:33 26 4
gpt4 key购买 nike

我试图编写在某个字符串中搜索字符串的函数。例如:“qwerty” => 搜索键“卡萨兹qertyqwerty”程序返回 1,因为在字符串中找到了 qwerty。

我的代码功能是:

int normal(char *str, char *str2)
{
int temp=0;
while(*str)
{
while(*str2)
{
if(*str == *str2)
{
temp+=1;
}
else if(temp == strlen(str2))
{
printf("%d", temp/strlen(str2));
}
str2++;
str++;
}
}
return 0;
}

程序中到底有什么问题(逻辑上)?

最佳答案

正确的答案显然是使用strtstr。但如果您仍然想知道为什么您的代码不起作用,那是因为您在递增的 str2 上调用了 strlen 。您应该首先在函数开头计算它,然后在完成字符比较后将 temp 与它进行比较。

关于c - 在字符串中查找字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6031888/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com