我正在尝试搜索字符串指针中的字符串。我不确定如何解释我正在努力达到的目标,但我会尽我所能。在“字符串指针”中寻找字符串 - C语言
比方说,我有两个字符串指针char *p = "hello world"
和char *q = "world"
,为world
是hello world
,所以我想返回一个指针*start
指向的*p
的w
。我希望这是有道理的,如果不是,请随时在下面发表评论。
注:不幸的是,我不能使用任何string.h
库函数,除了strlen()
,而且我不允许使用索引其实我不允许使用任何方括号[]
。
P.S.忽略所有printf
,因为他们在那里检查程序出错的地方。
#include <stdio.h>
#include <string.h>
int main(){
char *p = "hello world", *q = "world", *start;
int i, count = 0;
printf("%c\n", *p);
for (i = 0; i < strlen(p); i++){
printf("p: %c compares with q: %c\n", *p, *q);
if (*p == *q){ // tried: if (p == q)
start = p;
printf("start: %s\n", start);
while (*p == *q){ // tried: while (p == q)
printf("p: %c compares with q: %c\n", *p, *q);
count ++;
p ++;
q ++;
if (count == strlen(q)){
printf("Found it\n");
return *start;
}
}
}
p ++;
}
printf("Not Found\n");
return 0;
}
只要它碰到w
它就会提前退出循环。我不知道为什么它这样做? 这是我的问题。
输出:
号码:ħ其中q进行比较:瓦特
号码:È其中q进行比较:瓦特
号码:升其中q进行比较:瓦特
p:l与q相比较:w
p:o与q相比较:w
号码:比较符合Q:W
未找到
编辑:
gcc -Wall filename.c
编译器不给我任何类型的警告/错误的。
感谢您指出我所犯的错误。 :) –