专业的编程技术博客社区

网站首页 > 博客文章 正文

C++趣味实用小实例:不使用变量实现求字符串长度的函数

baijin 2024-09-21 12:44:33 博客文章 3 ℃ 0 评论

这里的字符串是指C风格的字符串,也就是以'\0'结尾的字符数组。

通常,遍历字符串的操作也以'\0'为标志值。

以下实例分别以使用变更和不使用变量使用递归的方式来求字符串的长度:

#include<iostream>
using namespace std;
int Strlen1(const char*str)
{
	int len = 0;
	if(str==NULL)
		return 0;
	for(;*str++!='\0';)
		len++;
	return len;
}
int Strlen2(const char*str)
{
	if(*str!='\0')
		return 1+Strlen2(++str);
	else return 0;
}
int Strlen3(const char*str)
{
return *str=='\0'?0:(1+Strlen3(++str));
}
void main()
{
	
 cout<<Strlen1("a test")<<endl;
	cout<<Strlen2("a test")<<endl;
	cout<<Strlen3("a test")<<endl;
 system("pause");
}
/*
6
6
6
*/

-End-

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表