温馨提示×

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

小亿
74
2024-01-10 15:58:33
栏目: 编程语言

在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.

0