C语言中计算字符串长度的函数是strlen,但是如果字符串中含有特殊字符,比如'\0'(空字符),那么strlen函数会认为字符串在该特殊字符处结束,导致计算出的字符串长度不准确。此时可以使用自己实现的函数来计算字符串长度,如下所示:

#include <stdio.h>

int my_strlen(const char *str) {
    int len = 0;
    while (*str) {
        len++;
        str++;
    }
    return len;
}

int main() {
    const char str[] = "hello\0world";
    int len = my_strlen(str);
    printf("The length of string is %d.\n", len); // output: The length of string is 11.
    return 0;
}

在上面的代码中,my_strlen函数会遍历字符串中的每个字符,直到遇到'\0'为止。这样可以确保计算出的字符串长度是准确的。


原文地址: http://www.cveoy.top/t/topic/XYd 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录