2017-11-11 60 views
1

我想寫一個函數,它根據字母順序比較字符串不區分大小寫。沒有任何標準庫比較不同長度的字符串

char compare(char *x, char *y){ 
    while (*x != '\0'){ 
     if (tolower(*x) < tolower(*y)){ 
      return -1; 
     } 
     else if (tolower(*x) > tolower(*y)){ 
      return 1; 
     } 
     else{ 
      x++; 
      y++; 
     } 
    } 
return 0; 
} 

但是這個功能不能很好地與分享幾首字母(如字和雙關語)的話工作。所以我試圖修改它:

char compare(char *x, char *y){ 
if (len(*x) < len(*y)){ 
    while (*x != '\0'){ 
     if (tolower(*x) < tolower(*y)){ 
      return -1; 
     } 
     else if (tolower(*x) > tolower(*y)){ 
      return 1; 
     } 
     else{ 
      x++; 
      y++; 
     } 
    } 
//   all n letters are the same (case insensitive), where n is a length of x 
    if (*y != '\0') return -1; 
} 
else { 
    while (*y != '\0'){ 
     if (tolower(*x) < tolower(*y)){ 
      return -1; 
     } 
     else if (tolower(*x) > tolower(*y)){ 
      return 1; 
     } 
     else{ 
      x++; 
      y`++; 
     } 
    } 
//   all n letters are the same (case insensitive), where n is a length of y 
    if (*x != '\0') return 1; 
} 
return 0; 
} 

但它沒有工作。我怎樣才能修改這個功能,使'文字遊戲'會比'文字'更大?

+0

你不能用'stricmp'吧? –

+0

存在打印錯誤,而不是++和b ++寫入x ++&y ++以及len(* x)如何工作。 – achal

+0

@ Jean-FrançoisFabre不是我不能,我只是不想 – jakes

回答

1

你的第一次嘗試是(幾乎)還好,只是需要對於你提出

char compare(const char *x, const char *y){ 
    while ((*x != '\0') && (*y != '\0')) { // testing y for symmetry 
     if (tolower(*x) < tolower(*y)){ 
      return -1; 
     } 
     else if (tolower(*x) > tolower(*y)){ 
      return 1; 
     } 
     else{ 
      x++; 
      y++; 
     } 
    } 
// added conditions to handle shorter/longer strings 
if (*x == '\0') 
    { 
     if (*y == '\0') 
     { 
     return 0; 
     } 
     else 
     { 
     return -1; 
     } 
    } 
    return 1; 
} 

我已經刪除了長度測試問題的調整,增加了邏輯來處理你提到的情況。也許它不是最優化的代碼,但它的工作(也注意到,我測試在主迴路X & y絃線的一端)

我反對stricmp結果測試,我得到同樣的結果:

void test(const char*a,const char*b) 
{ 
    printf("test %s %s => %d, %d\n",a,b,compare(a,b),stricmp(a,b)); 
} 

int main(void) { 
    test("abc","aBcd"); 
    test("abc","aBcd"); 
    test("abc","aBc"); 
    test("abcdef","abC"); 
    test("abcdef","cdef"); 

} 

結果:

test abc aBcd => -1, -1 
test abc aBcd => -1, -1 
test abc aBc => 0, 0 
test abcdef abC => 1, 1 
test abcdef cdef => -1, -1