strlen
统计字符串中‘\0’前面出现的字符个数(不包含‘\0’)
返回类型:size_t,其实就是unsigned int,即无符号整型
方法一:计数器
#include <stdio.h>
#include <assert.h>
size_t my_strlen(const char* str)
{
size_t count = 0;
assert(str);
while (*str != '\0')
{
count++;
str++;
}
return count;
}
int main()
{
char arr[] = "abcdef";
size_t n = my_strlen(arr);//传的是arr首字符的地址
printf("%u\n", n);
return 0;
}
方法二:指针减指针
#include <stdio.h>
#include <assert.h>
size_t my_strlen(const char* str)
{
const char* p = str;
assert(str);
while (*p != '\0')
{
p++;
}
return p-str;
}
int main()
{
char arr[] = "abc";
size_t n = my_strlen(arr);
printf("%u\n", n);
return 0;
}
方法三:递归
#include <stdio.h>
#include <assert.h>
size_t my_strlen(const char* str)
{
assert(str);
if (*str == '\0')
{
return 0;
}
else
{
return 1 + my_strlen(str + 1);
}
}
int main()
{
char arr[] = "abcd";
size_t n = my_strlen(arr);
printf("%u\n", n);
return 0;
}
标签:arr,return,char,str,库函数,strlen,模拟,size
From: https://blog.csdn.net/2301_80247375/article/details/145228937