我很难弄清楚为什么我的代码没有遍历 if 语句直到找到正确的字符。
#include <stddef.h>
#include <stdio.h>
char * my_strstr(char * param_1, char * param_2) {
int i;
int j;
for (i = 0; param_1[i] != '\0'; i++) {
printf("this is a loop for j %c\n", param_1[i]);
for (j = 0; param_2[j] != '\0'; j++) {
printf("this is a loop for j %c\n", param_2[j]);
if (param_1[i] == param_2[j]) {
printf("figuring out this %c\n", param_1[i]);
j++;
i++;
return ¶m_1[i];
printf("figuring out this %c\n", param_1[i]);
}
}
}
}
int main() {
char * param_1 = "hello";
char * param_2 = "ello";
printf("This is the string %s \n", my_strstr(param_1, param_2));
return 0;
}
答案 0 :(得分:1)
我在下面粘贴了您的代码,并进行了一些编辑和评论,希望能有所帮助。
#include <stddef.h>
#include <stdio.h>
char * my_strstr(char * param_1, char * param_2) {
int i;
int j;
for (i = 0; param_1[i] != '\0'; i++) {
// this should say "loop for i" shouldn't it?
printf("this is a loop for j %c\n", param_1[i]);
// use a flag to determine if you have found a match or not
int found = 1;
for (j = 0; param_2[j] != '\0'; j++) {
/* you actually want to compare param_1[i + j] == param_2[j] here
(respecting bounds of course). */
if (! param_1[i + j] || param_1[i + j] != param_2[j]) {
found = 0;
break;
}
printf("this is a loop for j %c\n", param_2[j]);
/* i don't understand what the following code was meant to do but you will
rarely want to increment i and j outside of the for ()
if (param_1[i] == param_2[j]) {
printf("figuring out this %c\n", param_1[i]);
j++;
i++;
return ¶m_1[i];
printf("figuring out this %c\n", param_1[i]);
}
*/
}
// here you want to check if you found it, and return if so.
if (found) {
return ¶m_1[i];
}
}
// need a default for if it is never found:
return NULL;
}
int main() {
char * param_1 = "hello";
char * param_2 = "ello";
printf("This is the string %s \n", my_strstr(param_1, param_2));
return 0;
}