C语言字符串比较函数: strcmp()详解

在 C 语言中,strcmp() 函数是用来比较两个字符串的标准库函数。它接受两个字符串作为参数,并返回一个整数值,表示两个字符串的大小关系。

函数原型:

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

参数:

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

返回值:

  • 如果 str1 小于 str2,则返回负值。
  • 如果 str1 等于 str2,则返回 0。
  • 如果 str1 大于 str2,则返回正值。

使用示例:

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

int main() {
    char str1[] = "hello";
    char str2[] = "world";

    int result = strcmp(str1, str2);

    if (result < 0) {
        printf("'%s' is less than '%s'
", str1, str2);
    } else if (result > 0) {
        printf("'%s' is greater than '%s'
", str1, str2);
    } else {
        printf("'%s' is equal to '%s'
", str1, str2);
    }

    return 0;
}

应用场景:

  • 字符串比较和排序
  • 字符串匹配
  • 数据验证

注意事项:

  • strcmp() 函数是区分大小写的。
  • strcmp() 函数会逐个字符比较两个字符串,直到找到不同的字符或到达字符串末尾。

总结:

strcmp() 函数是 C 语言中非常常用的函数,它提供了一种简单有效的方法来比较字符串。了解 strcmp() 函数的用法和返回值可以帮助你更好地编写 C 程序。


原文地址: https://www.cveoy.top/t/topic/mxtW 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录