c语言字符串比较是否相等

883
2024/2/6 15:58:33
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在C语言中,可以使用strcmp函数来比较两个字符串是否相等。strcmp函数的原型如下:

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

该函数接受两个参数,分别是要比较的两个字符串。如果两个字符串相等,则返回值为0;如果str1小于str2,则返回值小于0;如果str1大于str2,则返回值大于0。以下是一个示例代码:

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

int main() {
    char str1[] = "Hello";
    char str2[] = "Hello";
    char str3[] = "Hi";

    if (strcmp(str1, str2) == 0) {
        printf("str1 and str2 are equal.\n");
    } else {
        printf("str1 and str2 are not equal.\n");
    }

    if (strcmp(str1, str3) == 0) {
        printf("str1 and str3 are equal.\n");
    } else {
        printf("str1 and str3 are not equal.\n");
    }

    return 0;
}

运行上述代码,输出结果如下:

str1 and str2 are equal.
str1 and str3 are not equal.

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: c语言生日祝福代码怎么写