给定字符串,任务是使用用户定义的函数或内置函数计算给定字符串的长度。
字符串的长度可以使用两种不同的方法来计算-
使用用户定义的函数-在这种情况下,遍历整个字符串,直到找到'\ o'为止,并通过递归调用函数将值递增1。
使用用户内置函数-strlen()
在“ string.h”头文件中定义了一个内置函数,该函数用于计算字符串的长度。此函数采用字符串类型的单个参数,并返回整数值作为长度。
Input-: str[] = "nhooo.com" Output-: length of string is 15 Explanation-: in the string “nhooo.com” 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[] = "nhooo.com" Call length(str) Stop
#include <bits/stdc++.h> using namespace std; //长度的递归函数 int length(char* str) { if (*str == '\0') return 0; else return 1 + length(str + 1); } int main() { char str[] = "nhooo.com"; cout<<"length of string is : "<<length(str); return 0; }
输出结果
如果我们运行以上代码,它将在输出后产生
length of string is : 15