温馨提示×

c语言怎么用strcmp比较两个字符串

小亿
87
2023-12-20 08:23:29
栏目: 编程语言

在C语言中,可以使用strcmp函数来比较两个字符串。该函数的原型为:

int strcmp(const char *s1, const char *s2);

其中,s1和s2分别为要比较的两个字符串。strcmp会返回一个整数值,表示字符串的比较结果。具体的比较规则如下:

  • 如果s1和s2相等,返回值为0;
  • 如果s1小于s2,返回值为负数;
  • 如果s1大于s2,返回值为正数。

下面是一个使用strcmp函数比较两个字符串的示例:

#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;
}

以上示例中,首先定义了两个字符串str1和str2,然后使用strcmp函数比较这两个字符串。根据返回值的不同,输出对应的比较结果。

0