C语言中字符串数组如何比较是否相同
时间: 2024-03-02 21:53:02 浏览: 132
在 C 语言中,字符串数组可以使用 strcmp 函数进行比较。strcmp 函数的原型为:
```c
int strcmp(const char *s1, const char *s2);
```
该函数接受两个参数,分别是要比较的两个字符串数组。如果两个字符串数组相同,函数返回值为 0。如果第一个字符串数组大于第二个字符串数组,函数返回值大于 0。如果第一个字符串数组小于第二个字符串数组,函数返回值小于 0。
以下是一个例子:
```c
#include <stdio.h>
#include <string.h>
int main()
{
char str1[100] = "hello";
char str2[100] = "world";
char str3[100] = "hello";
if (strcmp(str1, str2) == 0) {
printf("str1 and str2 are the same\n");
} else {
printf("str1 and str2 are different\n");
}
if (strcmp(str1, str3) == 0) {
printf("str1 and str3 are the same\n");
} else {
printf("str1 and str3 are different\n");
}
return 0;
}
```
输出结果为:
```
str1 and str2 are different
str1 and str3 are the same
```