strcmp函数用法

strcmp函数用法

strcmp 函数是 C 语言标准库中的一个函数,用于比较两个字符串的内容。它的定义在 <string.h> 头文件中。strcmp 函数会按照字符的 ASCII 码值逐个比较两个字符串的字符,直到遇到不同的字符或者字符串结束符 \0。

以下是 strcmp 函数的原型:

int strcmp(const char *str1, const char *str2);

参数

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

返回值

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

示例代码

#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"

注意事项

  1. strcmp 是区分大小写的。例如,"A" 和 "a" 会被认为是不同的字符。
  2. strcmp 函数在遇到第一个不同的字符时就会返回结果,不会比较整个字符串。
  3. 如果两个字符串完全相同(包括结束符 \0),函数返回 0。

如果需要不区分大小写的比较,可以使用 strcasecmp(在 POSIX 系统中,如 Linux)或 _stricmp(在 Windows 中)。不过,这些函数不是标准 C 库的一部分,因此在使用时需要注意跨平台的兼容性问题。