The Wayback Machine - https://web.archive.org/web/20240717180319/https://www.geeksforgeeks.org/program-for-length-of-a-string-using-recursion/
Open In App

Program for length of a string using recursion

Last Updated : 01 Aug, 2022
Improve
Suggest changes
Post a comment
Like Article
Like
Save
Share
Report

Given a string calculate length of the string using recursion. 

Examples: 

Input : str = "abcd"
Output :4

Input : str = "GEEKSFORGEEKS"
Output :13

We have discussed 5 Different methods to find length of a string in C++ 
How to find length of a string without string.h and loop in C?

Algorithm:

recLen(str)
{
   If str is NULL 
       return 0
   Else 
      return 1 + recLen(str + 1)
}

Implementation:

C++




// CPP program to calculate length of
// a string using recursion
#include <bits/stdc++.h>
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




<?php
// PHP program to calculate
// length of a string using
// recursion
  
// Function to
// calculate length
function recLen(&$str, $i)   
{
    // if we reach at the
    // end of the string
    if ($i == strlen($str))
        return 0;
    else
        return 1 +
               recLen($str,
                      $i + 1);
}
   
// Driver Code
$str = "GeeksforGeeks";
echo (recLen($str, 0));
 
// This code is contributed by
// Manish Shaw(manishshaw1)
?>


Javascript




<script>
 
// JavaScript program to calculate length of
// a string using recursion
 
/* Function to calculate length */
    function recLen(str)
    {
   
        // if we reach at the end of the string
        if (str == "")
            return 0;
        else
            return recLen(str.substring(1)) + 1;
    }
 
// Driver code
 
        let str ="GeeksforGeeks";
        document.write(recLen(str));
            
</script>


Output

13

Time Complexity : O(n) 
Auxiliary Space : O(n) for recursion call stack. 

Since this solution requires extra space and function call overhead, it is not recommended to use it in practice.



Previous Article
Next Article

Similar Reads

Why is Tail Recursion optimization faster than normal Recursion?
What is tail recursion? Tail recursion is defined as a recursive function in which the recursive call is the last statement that is executed by the function. So basically nothing is left to execute after the recursion call. What is non-tail recursion? Non-tail or head recursion is defined as a recursive function in which the recursive call is the f
4 min read
Length of longest palindromic sub-string : Recursion
Given a string S, the task is to find the length longest sub-string which is a palindromeExamples: Input: S = "aaaabbaa" Output: 6 Explanation: Sub-string "aabbaa" is the longest palindromic sub-string.Input: S = "banana" Output: 5 Explanation: Sub-string "anana" is the longest palindromic sub-string. Approach:The idea is to use recursion to break
8 min read
Lexicographically smallest permutation of a string that can be reduced to length K by removing K-length prefixes from palindromic substrings of length 2K
Given a binary string str of length N, and an integer K, the task is to find the lexicographically smallest permutation of the string str that can be reduced to length K by removal of every K-length prefix from palindromic substrings of length 2K. If no such permutation exists, print "Not Possible". Examples: Input: str = "0000100001100001”, K = 4O
14 min read
Minimize steps to form string S from any random string of length K using a fixed length subsequences
Given a string S consisting of N characters and a positive integer K, the task is to find the minimum number of operations required to generate the string S from a random string temp of size K and inserting the subsequence of any fixed length from the random string in the random string. If it is impossible to generate the string S, then print "-1".
12 min read
Convert a String to an Integer using Recursion
Given a string str representing a string, the task is to convert the given string into an integer.Examples: Input: str = "1234" Output: 1234Input: str = "0145" Output: 145 Approach: Write a recursive function that will take the first digit of the string and multiply it with the appropriate power of 10 and then add the recursive result for the subst
4 min read
Product of nodes at k-th level in a tree represented as string using Recursion
Prerequisite: Product of nodes at k-th level in a tree represented as stringGiven an integer ‘K’ and a binary tree in string format. Every node of a tree has value in range from 0 to 9. We need to find product of elements at K-th level from the root. The root is at level 0.Note: Tree is given in the form: (node value(left subtree)(right subtree))Ex
5 min read
Move all occurrence of letter 'x' from the string s to the end using Recursion
Given a string s, our task is to move all the occurrence of letter x to the end of the string s using recursion.Note: If there are only letter x in the given string then return the string unaltered. Examples: Input: s= "geekxsforgexxeksxx" Output: geeksforgeeksxxxxx Explanation: All occurrence of letter 'x' is moved to the end. Input: s = "xxxxx" O
8 min read
Decode a string recursively encoded as count followed by substring | Set 2 (using Recursion)
An encoded string str is given. The pattern in which the string is encoded is as follows. &lt;count&gt;[sub_str] ==&gt; The substring 'sub_str' appears count times. The task is to decode this string str. Examples: Input: str = "1[b]"Output: bExplanation: The substring 'b' is repeated 1 time. Input: str = "2[ab]"Output: ababExplanation: The substrin
9 min read
Print reverse of a string using recursion
Write a recursive function to print the reverse of a given string. Code: C/C++ Code // C++ program to reverse a string using recursion #include &lt;bits/stdc++.h&gt; using namespace std; /* Function to print reverse of the passed string */ void reverse(string str) { if(str.size() == 0) { return; } reverse(str.substr(1)); cout &lt;&lt; str[0]; } /*
9 min read
Program to check if an array is palindrome or not using Recursion
Given an array. The task is to determine whether an array is a palindrome or not using recursion. Examples: Input: arr[] = {3, 6, 0, 6, 3}Output: Palindrome Input: arr[] = {1, 2, 3, 4, 5}Output: Not Palindrome Approach: Base case: If array has only one element i.e. begin == end then return 1, also if begin&gt;end which means the array is palindrome
4 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg