三种方法求字符串长度

在求字符串长度时,第一时间会想到运用strlen这个函数,但对于初学者来说,除了掌握这个函数之外,还应当自己写函数来实现相似的功能。

接下来我列举了三种方法来求字符串长度,供大家参考:

(1)运用strlen

注意点:运用该函数时需注意包含string.h头函数

#include<stdio.h>
#include<string.h>
int main()
{
	char ch[] = "abcdefg";
	int len = strlen(ch);
	printf("字符串长度为%d\n", len);
	return 0;
}

(2)自定义my_strlen函数

注意点:拿“abcdefg”字符串举个例子,它在内存中存储的样式为a b c d e f g \0,统计字符串的长度也就是要统计“\0”之前的字符有多少。

那么,设置两个变量,一个用来依次访问字符串中的每一个字符,一个用来统计数量。

#include<stdio.h>
int my_strlen(char ch[])
{
	int i = 0;
	int num = 0;
	while (ch[i] != '\0')
	{
		i++;
		num++;
	}
	return num;
}
int main()
{
	char ch[] = "abcdefg";
	int len = my_strlen(ch);
	printf("字符串长度为%d\n", len);
	return 0;
}

(3)用字符型指针和递归来实现

注意点:求"abcdefg"的字符串长度,可以将其看成1+my_strlen(bcdefg)->1+1+my_strlen(cdefg)->1+1+1+my_strlen(defg)->...一直到指针指向'\0'为止。

#include<stdio.h>
int my_strlen(char* pr)
{
	if (*pr != '\0')
	{
		return my_strlen(pr + 1) + 1;
	}
	else
	{
		return 0;
	}
}
int main()
{
	char ch[] = "abcdefg";
	int len = my_strlen(ch);
	printf("字符串长度为%d\n", len);
	return 0;
}

  • 33
    点赞
  • 165
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值