2013-07-18 37 views
0

作爲一種練習,我想盡可能實現字符串比較。 的代碼如下:一行中的字符串比較

#include <stdio.h> 

int strcmp(const char* a, const char* b) 
{ 
    for(;a && b && *a && *b && *a++==*b++;);return *a==*b; 
} 


int main() 
{ 
    const char* s1 = "this is line"; 
    const char* s2 = "this is line2"; 
    const char* s3 = "this is"; 
    const char* s4 = "this is line"; 


    printf("Test 1: %d\n", strcmp(s1, s2)); 
    printf("Test 2: %d\n", strcmp(s1, s3)); 
    printf("Test 3: %d\n", strcmp(s1, s4)); 
    printf("Test 4: %d\n", strcmp(s1, s1)); 
    printf("Test 5: %d\n", strcmp(s2, s2)); 

    return 0; 
} 

結果是:

Test 1: 0 
Test 2: 0 
Test 3: 1 
Test 4: 0 
Test 5: 0 

什麼是與自己的字符串比較的情況下回事?

注意: 我知道有一個較短的解決方案,但我想自己找到它。

編輯: 編譯器是在Ubuntu下的gcc

+2

你需要'()'來單獨''&&? –

+1

我在vs2008中運行你的代碼,結果是'0 0 1 1 1'。 –

+5

如果它們不提供相同的功能,請不要將它們與標準庫中的函數調用相同。當你這樣做的時候,你會以微妙的方式打破許多事情。 – Art

回答

3

如果它們不提供相同的功能,請不要將它們與標準庫中的函數調用相同。當你這樣做的時候,你會以微妙的方式打破許多事情。顯然這是這裏的錯誤。

在這裏添加更多有用的評論。改用while循環。不要檢查參數是否爲NULL,這是糟糕的風格,即使for循環因此而結束,return語句也會崩潰,因爲它將取消引用NULL。

1

如果您發現兩個本地字符不相等,你遞增指針ab儘管如此,然後返回*a==*b所以你返回比較後面的字符在弦不同的地方的結果。更好地那樣做:

for(;*a && *b && *a==*b; a++, b++) ; 
return *a==*b; 

而且請,請重命名功能。這是evereything但strcmp。

編輯沒有解釋測試用例4,但這是通過使用功能名稱strcmp()作爲其他答案告訴解釋。

2

我用GCC-4.4.7測試了你的代碼,得到了同樣的結果。 GCC頁面描述優化strcmphttp://gcc.gnu.org/projects/optimize.html

GCC可以優化STRCMP(和memcmp),其中一個字符串是恆定的,以比較連續字節已知常數的人在線。

重命名功能,你將下面讓您預期的結果:

$ cc yourcode.c 
$ ./a.out 
Test 1: 0 
Test 2: 0 
Test 3: 1 
Test 4: 0 
Test 5: 0 
$ cc -D strcmp=strcmp1 yourcode.c 
$ ./a.out 
Test 1: 0 
Test 2: 0 
Test 3: 1 
Test 4: 1 
Test 5: 1 
0

繼承人正確的strcmp

int    my_strcmp(char *str1, char *str2) 
{ 
    int   i; 

    i = 0; 
    while (str1[i] || str2[i]) 
    { 
     if (str1[i] != str2[i]) 
     return (str1[i] - str2[i]); 
     i++; 
    } 
    return (0); 
} 
+0

關鍵字是** short ** – Alex

+0

它會更清晰並使用相同的資源 – Saxtheowl