有三种方法解决这个问题
方法一:设置一个整形计数器,遍历整个字符串。
方法二:设置一个char*变量标记字符串的首地址,通过指针相减得到字符串的长度
方法三:采用函数递归的方法
第一种,采用计数器方法,定义一个变量来计数,模拟实现strlen
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
int my_strlen(const char *s)//定义为const,是希望此字符串不被修改
{
assert(s);//判断指针s是否为空(空指针是不能够解引用的)
int count = 0;//定义一个变量,通过它的变化来显示字符串的长度
while (*s)
{
count++;
s++;
}
return count;
}
int main()
{
int count = 0;
char str[100] = { 0 };
printf("str:");//可随机输入一个字符串,计算它的长度
scanf("%s", &str);
count=my_strlen(str);
printf("%d\n", count);
system("pause");
return 0;
}
第二种,采用指针相减(指针—指针)的方法模拟实现strlen
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
int my_strlen( const char *s)//定义为const,是希望此字符串不被修改
{
char *p = s;//把字符串的首地址传给指针p
assert(p);//判断指针p是否为空(空指针是不能够解引用的)
while (*p != '\0')
{
p++;//产生了整个字符串
}
return p - s;//通过指针相减,返回字符串的长度
}
int main()
{
int num = 0;
char str[100] = { 0 };
printf("str:");//可随机输入一个字符串,计算它的长度
scanf("%s", &str);
num=my_strlen(str);
printf("%d\n", num);
system("pause");
return 0;
}
第三种,采用函数递归的方法模拟实现strlen
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
int my_strlen(const char *s)//定义为const,是希望此字符串不被修改
{
assert(s);判断指针s是否为空(空指针是不能够解引用的)
if (*s == '\0')//如果字符串的长度为0,*s为'\0' ,此表达式为真, 执行return 0;语句
return 0;
else
return 1+ my_strlen(s+1);
}
int main()
{
int num = 0;
char str[100] = {0};
printf("str:");//可随机输入一个字符串,计算它的长度
scanf("%s", &str);
num=my_strlen(str);
printf("%d\n", num);
system("pause");
return 0;
}