Program for length of a string using recursion
Last Updated :
01 Aug, 2022
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++
#include <bits/stdc++.h>
using namespace std;
int recLen( char * str)
{
if (*str == '\0' )
return 0;
else
return 1 + recLen(str + 1);
}
int main()
{
char str[] = "GeeksforGeeks" ;
cout << recLen(str);
return 0;
}
|
Java
import java.util.*;
public class GFG{
private static int recLen(String str)
{
if (str.equals( "" ))
return 0 ;
else
return recLen(str.substring( 1 )) + 1 ;
}
public static void main(String[] args)
{
String str = "GeeksforGeeks" ;
System.out.println(recLen(str));
}
}
|
Python3
str = "GeeksforGeeks"
def string_length( str ) :
if str = = '':
return 0
else :
return 1 + string_length( str [ 1 :])
print (string_length( str ))
|
C#
using System;
public class GFG{
private static int recLen( string str)
{
if (str.Equals( "" ))
return 0;
else
return recLen(str.Substring(1)) + 1;
}
public static void Main()
{
string str = "GeeksforGeeks" ;
Console.WriteLine(recLen(str));
}
}
|
PHP
<?php
function recLen(& $str , $i )
{
if ( $i == strlen ( $str ))
return 0;
else
return 1 +
recLen( $str ,
$i + 1);
}
$str = "GeeksforGeeks" ;
echo (recLen( $str , 0));
?>
|
Javascript
<script>
function recLen(str)
{
if (str == "" )
return 0;
else
return recLen(str.substring(1)) + 1;
}
let str = "GeeksforGeeks" ;
document.write(recLen(str));
</script>
|
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.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...