国际访客建议访问 Primers 编程伙伴 国际版站点 > C 教程 > strcmp 以获得更好的体验。

# C 语言标准库函数 strcmp

在头文件 string.h 中定义。
/*********************************************
 * @brief 比较两个字符串是否相同
 * @param lhs 要比较的字符串
 * @param rhs 要比较的字符串
 * @return 字符串的差异
 ********************************************/
int strcmp(const char* lhs, const char* rhs);

!subtitle:说明

比较两个字符串是否相同。

!subtitle:参数

  • lhs - 要比较的字符串

  • rhs - 要比较的字符串

!subtitle:返回值

  • 如果字符串相同,则返回 0

  • 如果字符串不同,则返回 lhs[i] - rhs[i]i 是第一个不同字符的索引

    • 返回负值说明按照字典序 lhsrhs 之前

    • 返回正值说明按照字典序 lhsrhs 之后

# 示例

#include <stdio.h>
#include <string.h>

int main(void)
{
    printf("%d\n", strcmp("hello", "hello"));   // 输出 0,相同
    printf("%d\n", strcmp("ABC", "ABCD"));      // 输出 -68,即 0 - 'D'
    printf("%d\n", strcmp("AAA9", "AAA6"));     // 输出 3,即 '9' - '6'

    return 0;
}

运行结果:

0
-68
3

# 推荐阅读

# 参考标准

  • C23 standard (ISO/IEC 9899:2024):

    • 7.24.4.2 The strcmp function (p: TBD)

  • C17 standard (ISO/IEC 9899:2018):

    • 7.24.4.2 The strcmp function (p: TBD)

  • C11 standard (ISO/IEC 9899:2011):

    • 7.24.4.2 The strcmp function (p: 365-366)

  • C99 standard (ISO/IEC 9899:1999):

    • 7.21.4.2 The strcmp function (p: 328-329)

  • C89/C90 standard (ISO/IEC 9899:1990):

    • 4.11.4.2 The strcmp function

本文 更新于: 2025-11-27 09:38:10 创建于: 2025-11-27 09:38:10