1、使用 strcmp 函数
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "Hello";
char str2[] = "World";
if (strcmp(str1, str2) == 0) {
printf("Strings are equal\n");
} else {
printf("Strings are not equal\n");
}
return 0;
}
2、手动比较字符数组
#include <stdio.h>
int compareStrings(char *str1, char *str2) {
while (*str1 && *str2 && (*str1 == *str2)) {
str1++;
str2++;
}
if (*str1 == '\0' && *str2 == '\0') {
return 0; // strings are equal
} else {
return 1; // strings are not equal
}
}
int main() {
char str1[] = "Hello";
char str2[] = "World";
if (compareStrings(str1, str2) == 0) {
printf("Strings are equal\n");
} else {
printf("Strings are not equal\n");
}
return 0;
}
3、递归比较字符串
#include <stdio.h>
int compareStringsRecursive(char *str1, char *str2) {
if (*str1 != *str2) {
return 1; // strings are not equal
}
if (*str1 == '\0' && *str2 == '\0') {
return 0; // strings are equal
}
return compareStringsRecursive(str1 + 1, str2 + 1);
}
int main() {
char str1[] = "Hello";
char str2[] = "World";
if (compareStringsRecursive(str1, str2) == 0) {
printf("Strings are equal\n");
} else {
printf("Strings are not equal\n");
}
return 0;
}
4、使用指针进行逐字符比较
#include <stdio.h>
int compareStringsPointer(char *str1, char *str2) {
while (*str1 && *str2) {
if (*str1 != *str2) {
return 1; // strings are not equal
}
str1++;
str2++;
}
if (*str1 == '\0' && *str2 == '\0') {
return 0; // strings are equal
} else {
return 1; // strings are not equal
}
}
int main() {
char str1[] = "Hello";
char str2[] = "World";
if (compareStringsPointer(str1, str2) == 0) {
printf("Strings are equal\n");
} else {
printf("Strings are not equal\n");
}
return 0;
}
5、比较字符串长度后逐字符比较
#include <stdio.h>
int compareStringsLength(char *str1, char *str2) {
int len1 = 0, len2 = 0;
// Calculate length of both strings
while (str1[len1] != '\0') {
len1++;
}
while (str2[len2] != '\0') {
len2++;
}
// Compare lengths
if (len1 != len2) {
return 1; // strings are not equal
}
// Compare characters
for (int i = 0; i < len1; i++) {
if (str1[i] != str2[i]) {
return 1; // strings are not equal
}
}
return 0; // strings are equal
}
int main() {
char str1[] = "Hello";
char str2[] = "World";
if (compareStringsLength(str1, str2) == 0) {
printf("Strings are equal\n");
} else {
printf("Strings are not equal\n");
}
return 0;
}