求字符串长度(递归)

法一:一般方法

#include<stdio.h>
#include<stdlib.h>
int my_strlen(const char *str)
{
int count = 0;
while (*str++ != ‘\0‘)
{
++count;
}
return count;
}
int main()
{
char *p = "hello";
int ret = my_strlen(p);
printf("%d\n",ret);
system("pause");
return 0;
}

结果:

5

法二:递归

#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 *p = "hello";
int ret = my_strlen(p);
printf("%d\n",ret);
system("pause");
return 0;
}
时间: 2024-08-03 15:30:09

求字符串长度(递归)的相关文章

字符串操作1 - 递归与非递归两种方法求字符串长度

1 //递归求字符串的长度 2 int RecurseLength(const char *str) 3 { 4 if(str == NULL || *str == '\0') 5 return 0; 6 7 if(*str == '\0') 8 return 0; 9 return RecurseLength(str+1) + 1;//返回当前字符数,再递归处理下一个字符 10 } 11 12 13 14 15 16 //非递归求字符串长度 17 int NonRecurseLength(co

求字符串长度函数实现的三种方法

/* Date: 10/03/19 12:49 Description: 求字符串长度函数实现的三种方法*/ #include<stdio.h> int strlen1(char *s);int strlen2(char *s);int strlen3(char *s); int main(void) { char str[]="The function to test my length."; printf("The length1 is:%d\n",

数组-----求字符串长度

//求字符串长度 #include"stdafx.h" #include<iostream> using namespace std; void main(){ char s[201]; int i = 0; cout << "Please enter a string(ended with enter):" << endl; cin.getline(s, 200); //cin.getline()的使用 while (s[i])

笔试题: 不使用中间变量求const字符串长度,即实现求字符串长度库函数strlen函数

笔试题: 不使用中间变量求const字符串长度,即实现求字符串长度库函数strlen函数. 函数接口声明如下:int my_strlen(const char *p); strlen函数实际完成的功能是从代表该字符串的第一个地址开始遍历,直到遇到结束符'\0'. 而返回的长度大小不包括'\0'. #include <stdio.h> #include <assert.h> //使用中间变量 //int my_strlen(const  char *str) //{ //   ass

求字符串长度 strlen(数组指针两种方式)

问题: 求字符串中所含有字符的个数(包括空格),即求字符串长度: #include <stdio.h> #include <assert.h> int _strlen(const char* str) { assert(str != NULL); int i=0; for(;*str++!='\0';i++); //for(;str++!=NULL;i++);//有些说这句也可以,但执行结果是死循环,str++即使越界也未必为NULL; return i; } int _strle

【C语言】实现一个函数求字符串长度(不能创建第三方变量)

//实现一个函数求字符串长度(不能创建第三方变量) #include <stdio.h> #include <assert.h> int my_strlen(const char *p) { assert(p); if (*p == '\0') return 0; else return 1 + my_strlen(++p); } int main() { char *p = "abcdefg"; printf("%d\n", my_strl

【C语言】编写一个函数,求字符串长度

//编写一个函数,求字符串长度 #include <stdio.h> #include <assert.h> int my_strlen(const char *p) { int len=0; assert(p); while (*(p++)) { len++; } return len; } int main() { char *p = "abcdef"; printf("%d\n", my_strlen(p)); return 0; }

sizeof()和strlen()在求字符串长度时的差别

sizeof()函数输出字符串长度时会把结束符计算在内: strlen()函数输出字符串长度时不会把结束符计算在内. 如图:

编写一个求字符串长度的函数strlen(),再用strlen()函数编写一个函数reverse(s)的倒序递归程序,使字符串s逆序-简单

源程序: #include < iostream > #include < string > using namespace std; int strlen(char *str) { int len = 0; while (str[len] != '\0') { len++; } return len; } void revers(char *b) { char c; int j, len; len = strlen(b); j = len / 2 - 1; while (j &g