第一种,使用递归(不创建变量)
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
int my_strlen(const char *str)
{
if (*str == '\0')
return 0;
else
return 1 +my_strlen(str + 1);
}
int main()
{
char str[20] = { 0 };
printf("str:");
scanf("%s", &str);
int len = my_strlen(str);
printf("%d\n", len);
system("pause");
return 0;
}
第二种,创建变量
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include <stdlib.h>
#include <assert.h>
int my_strlen(const char*str)
{
int count = 0;
if (*str == NULL)
{
return count = 0;
}
else
{
while (*str++)
{
count++;
}
/*while (*str)
{
count++;
str++;
}也可以使用这种方式实现while循环*/
return count;
}
}
int main()
{
char str[20] = { 0 };
printf("str:");
scanf("%s", &str);
int count = my_strlen(str);
printf("%d\n", count);
system("pause");
return 0;
}
此篇不是很全面,可以查看下一篇:用三种方法模拟实现strlen函数。