作爲一種練習,我想盡可能實現字符串比較。 的代碼如下:一行中的字符串比較
#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
。
你需要'()'來單獨''&&? –
我在vs2008中運行你的代碼,結果是'0 0 1 1 1'。 –
如果它們不提供相同的功能,請不要將它們與標準庫中的函數調用相同。當你這樣做的時候,你會以微妙的方式打破許多事情。 – Art