所以我試圖通過創建一個基本函數strend
來獲得指針/數組的掌握,如果在給定字符串的末尾出現子字符串,則返回1
,否則返回0
。我意識到我可以通過測量一個char數組的長度,從這個長度減去子串的長度,並在那裏啓動我的程序來完成這個任務,但我希望按照我的函數來獲得更強的抓握指針算術。因此,這裏的程序:指針字符串解析算法
#include <stdio.h>
#define NELEMS(x) (sizeof(x)/sizeof(x[0]))
int strend(char *string, char *substring, int substringLength){
int count; /*keep track of how many number of chars that match in a row*/
while(*string != '\0'){
count = 0;
while(*string == *substring){
if (count + 1 == substringLength) return 1; /*if matches = length of str*/
count++;
string ++;
substring ++;
}
if (count == 0) string++; /*only increment outer loop if inner loop has done no work*/
else {
substring - count; /*reset substring, don't increment string... BUGGY*/
}
}
return 0;
}
int main(){
char string[] = "John Coltrane";
char substring[] = "Coltrane";
int substringLength = NELEMS(substring);
printf("%d \n", strend(string, substring, substringLength));
char string2[] = "John Coltrane is Awesome Coltrane";
char substring2[] = "Coltrane";
int substringLength2 = NELEMS(substring);
printf("%d \n", strend(string2, substring2, substringLength2));
return 1;
}
在第一次測試字符串,字符串,字符串,我得到正確的結果,返回1,因爲「雷恩」是在字符串的結尾。同樣,如果我從string2中取出「Coltrane」,我會得到正確的結果,返回0,因爲字符串不會以Coltrane結尾。
但是,對於上面看到的string2版本,我也會得到零,問題在於strend
在我迭代它之後不會重置substring
,並在它匹配主串的一部分時遞增它。當子字符串的第一個實例位於字符串的末尾時,這沒有問題,但是當有兩個實例時(如在string2中)時沒有。我認爲substring - count
會將指針遞減回到子字符串數組的開頭,但它似乎沒有這樣做。
如果我用substring--
更改了該表達式,它確實顯示了子字符串的最後一個字符,但像for(int i = 0; i < count; i++, substring--)
這樣的表達式真的是唯一的方法嗎?
編輯:更換substring - count
與for(; count > 0; count--, substring--)
似乎是一個非常優雅的班輪,它適用於我,但我仍然有一種直覺,有更好的辦法。
這應該是' - ='(複合賦值)。 – Jon 2013-02-20 21:30:16