我在C中很新,我想知道如何找出兩個相同字符之間的距離。找到兩個字符之間的距離
例如;我們有字符串「蝙蝠俠」,而字母「a」會給我們第一個「a」和第二個/最後一個「a」之間的距離。在這種情況下,我們會有2個結果。
這是我的代碼到目前爲止,但我很不確定該怎麼做 - 所以請幫助我。而且我也很確定這不是一個有效的方法。
int distance(char* s, char c) {
int res = -1;
int i = 0;
while(s[i]) {
int j = i+1;
while(s[j]) {
if (s[j] == c) {
res = j-i;
break;
}
j++;
}
i++;
}
return res-1;
}
我知道我做錯了什麼,但我不知道是什麼。 在此先感謝
我建議你花一些時間來閱讀[如何調試小程序(https://ericlippert.com/2014/03/05/how-to-debug-small-programs/)由埃裏克利珀,並學習如何使用調試器逐行執行代碼。 –
目前還不清楚你在問什麼。你是說這個程序不工作?如果不是的話,那究竟是什麼問題,以及你到目前爲止所進行的調查? – lurker
你不需要兩個嵌套循環,一個會做。當你發現'c'設置'lastindex'時,如果'firstindex'從未設置過,那麼也要設置它。確保你處理的角落案件,如一次或沒有。 –