您的位置首页百科知识

strcmp函数用法举例

strcmp函数用法举例

的有关信息介绍如下:

strcmp函数用法举例

strcmp 函数用法举例

strcmp 是 C 标准库中的一个函数,用于比较两个字符串。它定义在 <string.h> 头文件中。该函数按字典顺序(ASCII 值)比较两个字符串,并返回一个整数来表示它们之间的关系。

函数原型

int strcmp(const char *str1, const char *str2);
  • 参数

    • str1:指向第一个要比较的字符串的指针。
    • str2:指向第二个要比较的字符串的指针。
  • 返回值

    • 如果返回值小于 0,表示 str1 小于 str2。
    • 如果返回值等于 0,表示 str1 等于 str2。
    • 如果返回值大于 0,表示 str1 大于 str2。

使用示例

以下是一些使用 strcmp 函数的例子:

示例 1: 基本比较
#include <stdio.h> #include <string.h> int main() { char str1[] = "Hello"; char str2[] = "World"; char str3[] = "Hello"; int result1 = strcmp(str1, str2); int result2 = strcmp(str1, str3); if (result1 < 0) { printf("'%s' is less than '%s'.\n", str1, str2); } else if (result1 > 0) { printf("'%s' is greater than '%s'.\n", str1, str2); } else { printf("'%s' is equal to '%s'.\n", str1, str2); } if (result2 < 0) { printf("'%s' is less than '%s'.\n", str1, str3); } else if (result2 > 0) { printf("'%s' is greater than '%s'.\n", str1, str3); } else { printf("'%s' is equal to '%s'.\n", str1, str3); } return 0; }

输出:

'Hello' is less than 'World'. 'Hello' is equal to 'Hello'.
示例 2: 比较不同长度的字符串
#include <stdio.h> #include <string.h> int main() { char str1[] = "apple"; char str2[] = "applepie"; int result = strcmp(str1, str2); if (result < 0) { printf("'%s' is less than '%s'.\n", str1, str2); } else if (result > 0) { printf("'%s' is greater than '%s'.\n", str1, str2); } else { printf("'%s' is equal to '%s'.\n", str1, str2); } return 0; }

输出:

'apple' is less than 'applepie'.
示例 3: 处理大小写敏感的比较
#include <stdio.h> #include <string.h> int main() { char str1[] = "Apple"; char str2[] = "apple"; int result = strcmp(str1, str2); if (result < 0) { printf("'%s' is less than '%s'.\n", str1, str2); } else if (result > 0) { printf("'%s' is greater than '%s'.\n", str1, str2); } else { printf("'%s' is equal to '%s'.\n", str1, str2); } return 0; }

输出:

'Apple' is greater than 'apple'.

注意事项

  1. 大小写敏感:strcmp 是区分大小写的,即 'A' 和 'a' 被视为不同的字符。
  2. 空字符串:如果任一字符串为空字符串(例如 ""),则非空字符串会被认为更大。
  3. 未定义行为:如果任一指针为 NULL,则 strcmp 的行为是未定义的,通常会导致程序崩溃。

通过这些示例和说明,你应该能够理解和正确使用 strcmp 函数来比较字符串。