2013-02-20 71 views
0

所以我試圖通過創建一個基本函數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 - countfor(; count > 0; count--, substring--)似乎是一個非常優雅的班輪,它適用於我,但我仍然有一種直覺,有更好的辦法。

+2

這應該是' - ='(複合賦值)。 – Jon 2013-02-20 21:30:16

回答

1

這是不會改變任何變量的值的表達式:

substring - count; 

這是你如何改變變量的值:

substring -= count; 

在你的代碼的其他錯誤是隻在計數爲0時遞增字符串。如果存在像「Cole Slaw」這樣的部分匹配,該怎麼辦?

+0

但是我在內部while循環中增加了字符串和子字符串,所以如果我在count!= 0時做增量,我會跳過一個字母。迭代器會到達l,遞增到e,在條件失敗後退出while循環,然後遞增到「」字符而不檢查循環頂部的e(確保它不是'\ 0 「)。 – user1427661 2013-02-20 21:49:22

+0

但是在每次失敗之後,您需要在下一次傳遞之前遞減到每個字符串的開始位置。考慮當你試圖匹配字符串「aaaaf」。您可能會與「aaabaaaaf」進行部分匹配。 – stark 2013-02-20 22:07:11

+0

我不確定我是否遵循...唯一需要遞減的字符串是子字符串,因爲您需要從頭開始測試。實際的字符串不應該遞減。如果輸入inner for循環並失敗,主字符串仍會因爲字符串++而增加,所以除非不輸入內部循環(即count = 0),否則不希望再次遞增。同樣,由於子字符串 - = count,子字符串會遞減相同的數字,從而有效地重新設置它。 – user1427661 2013-02-20 22:19:24