C++ 用递归方式求字符串长度的程序
我们给出了一个字符串和一项任务:使用用户自定义函数或内置函数计算给定字符串的长度。
可以采用两种不同的方式计算字符串的长度——
- 使用用户自定义函数——用这种办法,我们可以遍历包含整个字符串,直到找到“\o”,并通过递归函数调用使值不断递增 1。
- 使用用户内置函数——“string.h”标头文件中定义了一个内置函数 strlen,用于计算字符串长度。此函数接受单一参数(字符串类型),并返回一个整数值作为长度。
示例
Input-: str[] = "tutorials point" Output-: length of string is 15 Explanation-: in the string “tutorials point” there are total 14 characters and 1 space making it a total of length 15.
算法
Start Step 1-> declare function to find length using recursion int length(char* str) IF (*str == '\0') return 0 End Else return 1 + length(str + 1) End Step 2-> In main() Declare char str[] = "tutorials point" Call length(str) Stop
示例
#include <bits/stdc++.h>
using namespace std;
//recursive function for length
int length(char* str) {
if (*str == '\0')
return 0;
else
return 1 + length(str + 1);
}
int main() {
char str[] = "tutorials point";
cout<<"length of string is : "<<length(str);
return 0;
}输出
如果我们运行以上代码它将生成以下输出
length of string is : 15
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP