//模拟实现strlen函数
#include <stdio.h>
#include <string.h>
#include<assert.h>
//方法一
int my_strlen(const char* str)
{
int count = 0;//计数器
assert(str != NULL);//断言,str不是一个空指针
while (str != '\0')
{
str++;
count++;
}
return count;
}
//方法二:递归方法
int my_strlen(const char* str)
{
assert(str != NULL);
if (*str != '\0')
{
return 1 + my_strlen(str + 1);
}
else
return 0;
}
//方法三:指针方法
int my_strlen(const char* str)
{
assert(str != NULL);//断言,str不是一个空指针
const char* start = str;
while (*str != '\0')//对str解引用得到对应地址的值
{
str++;
}
return str-start;//指针减去指针返回的是之间元素的个数
}
int main()
{
char arr[] = "abcdefg";
int ret = my_strlen(arr);
printf("%d", ret);
return 0;
}