递归函数mystrlen(char* buf,int N) 是用来实现统计字符串中第一个空字符前面的字符长度,实现?
递归函数要关注的问题:
退出条件、参数有哪些?返回值是什么?局部变量、全局变量、何时输出?会不会导致栈溢出?
#include <iostream>
#include <Windows.h>
#include <assert.h>
using namespace std;
int My_strlen(char* buf, int N) //此处N为输入长度,不是字符串实际长度
{
if (buf[0]==0 || N == 0)
{
return 0; //此时输出字符串实际长度为0
}
else if (N == 1)
{
return 1;
}
int t = My_strlen(buf, N / 2); //折半查找,此处取得的t代表N/2中是否有字符串的实际长度,如果字符串的实际长度是大于等于N/2的则需要继续递归,如果小于N/2则可直接返回
if (t < N / 2)
{
return t;
}
else
{
return (t + My_strlen(buf + N / 2, (N + 1) / 2)); //此时未找到字符串的实际长度,需要继续往后递归,小于N/2的部分不用在找
}
}
int main()
{
char str[] = { 'a', 'b', 'c', 'v','c', '\0', 'p', 'u', 'y' };
int yyp = My_strlen(str, 100);
cout <<"N为100时:"<< yyp << endl;
int www = My_strlen(str, 2);
cout << "N为2时:" << www << endl;
int zbb = My_strlen(str, 5);
cout << "N为5时:" << zbb << endl;
system("pause");
return 0;
}