对于一个采用字符数组存放的字符串str设计一个递归算法求其字符个数长度。要求先写出递归模型再写出对应的递归程序。注意一定要写完整包括主函数
递归模型:
- 如果字符串为空,则字符个数为0;
- 如果字符串不为空,字符个数为1加上剩余子串的字符个数。
递归程序:
#include <iostream>
using namespace std;
int strLength(char str[]) {
if (str[0] == '\0') { // 空字符串,长度为0
return 0;
} else { // 非空字符串,长度为1+子串长度
return 1 + strLength(str+1);
}
}
int main() {
char str[100];
cout << "请输入一个字符串:";
cin >> str;
cout << "字符串长度为:" << strLength(str) << endl;
return 0;
}
原文地址: https://www.cveoy.top/t/topic/b2U6 著作权归作者所有。请勿转载和采集!