第1种:计数器实现
定义一个计数器,当下一个字符不是’\0’的时候就自增。
#include <stdio.h>
#include <assert.h>
int my_strlen(const char* p)
{
int count = 0;
assert(p!=NULL);
while (*p != '\0')
{
count++;
p++;
}
return count;
}
第二种:指针运算实现
利用指针减去指针等于中间元素个数,如果后一个元素不是\0计数器就自增。
#include <stdio.h>
#include <assert.h>
int my_strlen(const char* arr)
{
assert(arr != NULL);
char* start = arr;
char* end = arr;
while (*end != '\0')
{
end++;
str++;
}
return end - start;
}
第三种:递归实现
int my_strlen(char* str)
{
assert(str != NULL);
if (*str=='\0')
return 0;
return my_strlen(str + 1) + 1;
}