我正在嘗試搜索字符串指針中的字符串。我不確定如何解釋我正在努力達到的目標,但我會盡我所能。在「字符串指針」中尋找字符串 - 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
編譯器不給我任何類型的警告/錯誤的。
感謝您指出我所犯的錯誤。 :) –