提问人:Omar Ghazi 提问时间:9/20/2023 最后编辑:chux - Reinstate MonicaOmar Ghazi 更新时间:9/21/2023 访问量:87
尝试在 c 中构建自己的 strstr() 函数?
Trying to build my own strstr() function in c?
问:
我正在尝试构建我的函数,它看起来一切正常
但是当我执行代码时,它什么也没返回;strstr()
这是我的功能:
#include <stdio.h>
char* ft_strstr(char *str, char *to_find) {
char *a;
char *b;
b = to_find;
if (!*b)
return (char*) str;
while (*str) {
if (*str != *b)
continue;
a = str;
while (1) {
if (!*b)
return (char*) str;
if (*a++ != *b++)
break;
}
str++;
b = to_find;
}
return (NULL);
}
int main() {
char string[] = "Hello from morroco";
char find[] = "from";
ft_strstr(string, find);
printf("%s", find);
return 0;
}
我不知道是什么。我必须尝试修复它,因为它对我来说看起来一切正常。
答:
2赞
Vlad from Moscow
9/20/2023
#1
此 if 语句中存在一个错误
if(*str != *b)
continue;
在这种情况下,指针不会增加,因此循环将是无限的。str
最好使用 for 循环代替 while 循环 as
for ( ; *str; ++str )
或者 while 循环可以如下所示
while (*str)
{
if( *str == *b )
{
a = str;
while(1)
{
if (!*b )
return (char *)str;
if (*a++ != *b++)
break;
}
}
str++;
b = to_find;
}
看来你的意思是
char *pos = ft_strstr(string , find);
if ( pos ) printf("%s", pos);
而不是
ft_strstr(string , find);
printf("%s", find);
注意函数应该像这样声明
char * ft_strstr( const char *str, const char *to_find);
并使用这样的铸件,如
return (char *)str;
如果参数具有应有的类型,则有意义。str
const char *
评论
0赞
Omar Ghazi
9/20/2023
谢谢 vlad ,但在这个主题中不允许循环,因为我必须使用 while,但我在第一个 while 循环的最后一个中增加了 str++,我试图将函数存放在 *p 中并打印它有条件但输出仍然相同,
0赞
Omar Ghazi
9/20/2023
我必须注意,我不能将 str 函数中的参数声明为 const
0赞
Vlad from Moscow
9/20/2023
@OmarGhazi 没有什么可以阻止你用 qualifer const 声明参数。此外,变量 a 和 b 必须使用限定符 const 声明。
2赞
Jonathan Leffler
9/20/2023
@OmarGhazi — 为什么不能将函数参数声明为 ?为什么你的“老师”会如此滥用语言?这对你来说是个坏兆头——你应该被教导如何编写好的 C 代码,并在明智的时候使用好的 C 代码。您是否也被限制在 C90 中?如果是这样,您必须开始担心您正在接受的教育标准。const
const
1赞
chux - Reinstate Monica
9/21/2023
@OmarGhazi限制,应该成为问题。for
const
评论
return (char *)str;
str
char *
strstr
函数和 C 的基础知识都有一些基本的误解。to_find
find
main
continue;
if(*str != *b)