实施strstr
我正在尝试从头开始编写 strstr 函数。我在调试器中逐行检查了我的代码,它工作正常。但是,它没有正确保存其搜索的子字符串的开头。因此,它没有正确返回它。我没有太多的编程经验,所以我的代码有点混乱和复杂。然而,它在大多数情况下确实有效。下面是我的代码(为我的教授发表评论,并让大家看看我做了什么)。 (另外,我的教授已经表示接受 goto 功能)
char *strgstr(const char *str1, const char *str2)
{
//I went through this function line by line with the debugger
//The only problem with it is when I go to save the location of the
//substring in str1.
//I posted a question on stackoverflow and I was able to get it to compile
//but it still doesn't save and return properly. The rest of the function works.
int len_str1=strlen(str1);
int len_str2=strlen(str2);
char *save_str=NULL;
int i=0;
for(; i<len_str1; i++)
{
there:
if(str1[i]==str2[0]) //checks if this is the beginning of str2
{
save_str=(char*)str1[i]; //This is where the problem is.
int j=0; //start at beginning of str2
for(;i<len_str1;i++) //index str1
{
if(j<len_str2) //checks if we've finished searching str2
{
if(str1[i]!=str2[j])
{
goto there;
}
j++;
}
else
{
return save_str; //does not return properly. I can't figure out how to save a particular point in the index to a pointer.
}
}
}
}
}
I am trying to write the strstr function from scratch. I went through my code line by line in the debugger and it works fine. However, it is not saving the start of the substring its searching for properly. And, therefore, it is not returning it properly. I do not have much programming experience so my code is a little messy and convoluted. However, it does work for the most part. Here is my code below (commented for my professor and for you all to see what I did). (also, my professor has already expressed his acceptance of the goto function)
char *strgstr(const char *str1, const char *str2)
{
//I went through this function line by line with the debugger
//The only problem with it is when I go to save the location of the
//substring in str1.
//I posted a question on stackoverflow and I was able to get it to compile
//but it still doesn't save and return properly. The rest of the function works.
int len_str1=strlen(str1);
int len_str2=strlen(str2);
char *save_str=NULL;
int i=0;
for(; i<len_str1; i++)
{
there:
if(str1[i]==str2[0]) //checks if this is the beginning of str2
{
save_str=(char*)str1[i]; //This is where the problem is.
int j=0; //start at beginning of str2
for(;i<len_str1;i++) //index str1
{
if(j<len_str2) //checks if we've finished searching str2
{
if(str1[i]!=str2[j])
{
goto there;
}
j++;
}
else
{
return save_str; //does not return properly. I can't figure out how to save a particular point in the index to a pointer.
}
}
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您编写的行
应该是(例如)
您的原始版本将字符的数值视为指针,这是完全错误的。
The line you've written as
should be (for example)
Your original version is treating the numerical value of the character as a pointer, which is completely wrong.
为什么需要这么复杂的代码?
Why do you need such complex code?
strstr 的 Java 代码
Java code for strstr