C语言中,通过指针比较字符串,可以深入理解指针的用法,掌握字符串在内存中的存储方式。同时,自定义的字符串比较函数可以根据实际需求进行优化。

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;
}

推荐文档

相关文档

大家感兴趣的内容

随机列表