strcmp("HelloWorld", "Hello World"); // 返回 >0,即 "HelloWorld" > "Hello World"
困惑:"Hello World" 多一個空格,長度更長,為何反而「較小」?
'H','e','l','l','o' 相同,繼續比較。str1[5] = 'W' (ASCII 87)str2[5] = ' ' (空格,ASCII 32)'W' (87) > ' ' (32),比較**立即結束**,返回正值 (表示 str1 > str2)。'o','r','l','d') **完全不參與比較**。| 返回值 | 含義 |
|---|---|
< 0 | str1 < str2 (按字典序) |
== 0 | str1 == str2 |
> 0 | str1 > str2 |
strcmp。#include
#include
int main() {
const char* a = "HelloWorld";
const char* b = "Hello World";
std::cout << "strcmp(a,b) = " << std::strcmp(a,b) << std::endl; // >0
std::cout << "'W'=" << int('W') << " ' '=" << int(' ') << std::endl; // 87 32
return 0;
}
char 有符號性實現定義,負值字符比較結果可能異常,建議轉 unsigned char 或用 std::string::compare。std::string 的 ==/compare(),避免 C 風格指針陷阱。理解「首異字符決定大小」規則,瞬間解開 strcmp 看似反直覺的結果。