strcmp() 函数用于比较两个字符串,返回 0 表示相等,负值表示第一个字符串小于第二个字符串,正值表示第一个字符串大于第二个字符串。

C 语言 strcmp() 函数用法
strcmp() 函数是 C 语言标准库中用于比较两个字符串的函数。其原型为:
<code class="c">int strcmp(const char *str1, const char *str2);</code>
用法
strcmp() 函数有两个参数,指向两个要比较的字符串的指针。该函数通过逐字符比较两个字符串,直到遇到第一个不同的字符或遇到字符串的空字符('\0')为止。
立即学习“C语言免费学习笔记(深入)”;
如果两个字符串相等,则 strcmp() 返回 0。如果 str1 小于 str2,则返回一个负值。如果 str1 大于 str2,则返回一个正值。
示例
<code class="c">#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "Hello";
char str2[] = "World";
int result = strcmp(str1, str2);
if (result == 0) {
printf("两个字符串相等。\n");
} else if (result < 0) {
printf("str1 小于 str2。\n");
} else {
printf("str1 大于 str2。\n");
}
return 0;
}</code>输出:
<code>str1 小于 str2。</code>
在这个示例中,strcmp() 函数返回 -1,表示 str1 小于 str2。
注意事项
- strcmp() 函数对大小写敏感。
- strcmp() 函数不考虑字符串长度,它只比较字符串中非空字符的顺序。
- strcmp() 函数可以用于比较任意类型的字符串,但通常用于比较由 null 终止的字符串。











