gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 22:03:28 24 4
gpt4 key购买 nike

这是我的代码,用于查找用户在给定字符串中输入的子字符串。

bool find_str(char *str, char const *substr) {
while(*str) {
if(*str++ == *substr) {
char const *a = substr;
while((*str++ == *++a)); /*empty*/
if(*a == '\0')
return true;
}
}
return false;
}
// If match found, then return true, else false

int main(void) {
printf("%d", find_str("ABCDEF", "CDE")); /* Return true in this case */
printf("%d", find_str("ABCDE", "CDE")); /* Return false in this case */

}

如评论中所述,只要以附加字符结尾,它就会返回 true。如果不是,则返回 false。我认为递增/递减运算符存在问题。但是我找不到怎么办?

最佳答案

这是因为您的代码决定仅在 执行比较之后停止查找 \0

*str++ == *++a

即使匹配发生在字符串末尾的空终止符上,此条件也将为 true,因此 while 循环将愉快地继续超出两个字符串的末尾超过空终止符,导致未定义的行为。

将条件更改为在 *a 为零时退出应该可以解决问题:

while((*str++ == *++a) && (*a));

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

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