C语言中,如何检查两个字符数列的每一项是否都相等
时间: 2024-10-08 11:09:41 浏览: 30
在C语言中,可以使用循环结构(如`for`或`while`)以及条件语句(如`if`)来逐个比较两个字符数列(字符串)的元素。下面是一个简单的示例,展示了如何通过`strcmp()`函数来检查每个字符是否相等:
```c
#include <stdio.h>
#include <string.h>
int checkEquality(char str1[], char str2[]) {
int len1 = strlen(str1);
int len2 = strlen(str2);
// 如果两个字符串长度不等,则它们不可能完全相等
if (len1 != len2) {
return 0; // 相符条件不成立
}
for (int i = 0; i < len1; i++) {
if (str1[i] != str2[i]) {
return 0;
}
}
return 1; // 所有字符都相等,返回1表示相符
}
int main() {
char str1[] = "Hello";
char str2[] = "World";
if (checkEquality(str1, str2)) {
printf("The strings are equal.\n");
} else {
printf("The strings are not equal.\n");
}
return 0;
}
阅读全文
相关推荐


















