C语言编程题计算两个字符串的长度

C语言中,有多种方法可以计算两个字符串的长度。五种方法展示了不同的计算字符串长度的方式,从使用标准库函数到手动实现。选择哪种方法取决于具体需求和场景。

1、使用 strlen 函数

#include <stdio.h>
#include <string.h>

int main() {
    char str1[] = "Hello";
    char str2[] = "World";
    
    int len1 = strlen(str1);
    int len2 = strlen(str2);
    
    printf("Length of str1: %d\n", len1);
    printf("Length of str2: %d\n", len2);
    
    return 0;
}

2、使用循环手动计算长度

#include <stdio.h>

int string_length(char *str) {
    int length = 0;
    while (str[length] != '\0') {
        length++;
    }
    return length;
}

int main() {
    char str1[] = "Hello";
    char str2[] = "World";
    
    int len1 = string_length(str1);
    int len2 = string_length(str2);
    
    printf("Length of str1: %d\n", len1);
    printf("Length of str2: %d\n", len2);
    
    return 0;
}

3、使用递归计算长度

#include <stdio.h>

int string_length_recursive(char *str) {
    if (*str == '\0') {
        return 0;
    } else {
        return 1 + string_length_recursive(str + 1);
    }
}

int main() {
    char str1[] = "Hello";
    char str2[] = "World";
    
    int len1 = string_length_recursive(str1);
    int len2 = string_length_recursive(str2);
    
    printf("Length of str1: %d\n", len1);
    printf("Length of str2: %d\n", len2);
    
    return 0;
}

4、使用指针遍历字符串

#include <stdio.h>

int string_length(char *str) {
    char *ptr = str;
    while (*ptr != '\0') {
        ptr++;
    }
    return ptr - str;
}

int main() {
    char str1[] = "Hello";
    char str2[] = "World";
    
    int len1 = string_length(str1);
    int len2 = string_length(str2);
    
    printf("Length of str1: %d\n", len1);
    printf("Length of str2: %d\n", len2);
    
    return 0;
}

5、使用宏定义计算长度(仅适用于字符串常量)

#include <stdio.h>

#define STRING_LENGTH(str) (sizeof(str) - 1)

int main() {
    char str1[] = "Hello";
    char str2[] = "World";
    
    int len1 = STRING_LENGTH(str1);
    int len2 = STRING_LENGTH(str2);
    
    printf("Length of str1: %d\n", len1);
    printf("Length of str2: %d\n", len2);
    
    return 0;
}

推荐阅读
cjavapy编程之路首页