C++ 递归算法求字符串字符个数
C++ 递归算法求字符串字符个数
本文介绍了使用递归算法计算字符串字符个数的 C++ 代码实现,并给出了详细的代码示例和解释。
递归模型:
设字符串 str 的长度为 n,字符个数为 count,则有以下递归关系:
- 当
n=0时,count=0; - 当
n>0时,count=1+count(str[1:n-1])。
递归程序:
#include <iostream>
using namespace std;
int count(char str[], int n) {
if (n == 0) return 0;
return 1 + count(str+1, n-1);
}
int main() {
char str[] = 'Hello world!';
int n = sizeof(str) / sizeof(char) - 1; // 不包括字符串末尾的'\0'
int cnt = count(str, n);
cout << "字符个数为:" << cnt << endl;
return 0;
}
输出结果:
字符个数为:12
原文地址: https://www.cveoy.top/t/topic/nm8t 著作权归作者所有。请勿转载和采集!