📜  使用递归来编程字符串的长度

📅  最后修改于: 2021-04-29 14:30:12             🧑  作者: Mango

由于使用递归的字符串>的计算长度。
例子:

Input : str = "abcd"
Output :4

Input : str = "GEEKSFORGEEKS"
Output :13

我们已经讨论了5种不同的方法来在C++中查找字符串的长度
如何找到没有字符串.h的字符串的长度并在C中循环?
算法

recLen(str)
{
   If str is NULL 
       return 0
   Else 
      return 1 + recLen(str + 1)
}
C++
// CPP program to calculate length of
// a string using recursion
#include 
using namespace std;
 
/* Function to calculate length */
int recLen(char* str)   
{
    // if we reach at the end of the string
    if (*str == '\0')
        return 0;
    else
        return 1 + recLen(str + 1);
}
 
/* Driver program to test above function */
int main()
{
    char str[] = "GeeksforGeeks";
    cout << recLen(str);
    return 0;
}


Java
// java program to calculate length of
// a string using recursion
import java.util.*;
 
public class GFG{
 
    /* Function to calculate length */
    private static int recLen(String str)
    {
 
        // if we reach at the end of the string
        if (str.equals(""))
            return 0;
        else
            return recLen(str.substring(1)) + 1;
    }
 
    /* Driver program to test above function */
    public static void main(String[] args)
    {
 
         
        String str ="GeeksforGeeks";
        System.out.println(recLen(str));
    }
}
 
// This code is contributed by Sam007.


Python3
# Python program to calculate
# length of a string using
# recursion
str = "GeeksforGeeks"
 
# Function to
# calculate length
def string_length(str) :
     
    # if we reach at the
    # end of the string
    if str == '':
        return 0
    else :
        return 1 + string_length(str[1:])
     
# Driver Code
print (string_length(str))
 
# This code is contributed by
# Prabhjeet


C#
// C# program to calculate length of
// a string using recursion
using System;
 
public class GFG{
 
    /* Function to calculate length */
    private static int recLen(string str)
    {
 
        // if we reach at the end of the string
        if (str.Equals(""))
            return 0;
        else
            return recLen(str.Substring(1)) + 1;
    }
 
    /* Driver program to test above function */
    public static void Main()
    {
 
         
        string str ="GeeksforGeeks";
        Console.WriteLine(recLen(str));
    }
}
 
// This code is contributed by vt_m.


PHP


Javascript


输出:

13

时间复杂度: O(n)
辅助空间: O(n)用于递归调用堆栈。

由于此解决方案需要额外的空间和函数调用开销,因此不建议在实践中使用它。