您会从标题 <string.h> 中寻找 strcmp()。
请注意,您需要一个字符串 — 'Lee' 不是字符串,而是一个多字符常量,这是允许的,但很少有用,尤其是因为表示是由编译器定义的,而不是 C 标准。
如果你想比较两个字符串——调用指向它们的指针first和second,然后你写:
if (strcmp(first, second) == 0) // first equal to second
if (strcmp(first, second) <= 0) // first less than or equal to second
if (strcmp(first, second) < 0) // first less than second
if (strcmp(first, second) >= 0) // first greater than or equal to second
if (strcmp(first, second) > 0) // first greater than second
if (strcmp(first, second) != 0) // first unequal to second
在我看来,这清楚地表明了比较是什么,因此应该使用符号。请注意,strcmp() 可以返回任何负值来表示“小于”或任何正值来表示“大于”。
你会找到喜欢的人:
if (strcmp(first, second)) // first unequal to second
if (!strcmp(first, second)) // first equal to second
IMO,它们的优点是简洁,但缺点是不如与零的明确比较清楚。 YMMV.
谨慎使用strncmp() 而不是strcmp(),这是在一个答案中建议的。如果你有:
if (strncmp(first, "command", 7) == 0)
那么如果first 包含"commander",则匹配有效。如果这不是你想要的,但你想使用strncmp(),你会写:
if (strncmp(first, "command", sizeof("command")) == 0)
这将正确拒绝"commander"。