Search⌘ K
AI Features

Solution Review: Length of a String

Understand how to determine a string's length recursively by testing an empty string as the base case and reducing the string step-by-step. This lesson helps you break down the problem, implement the recursive function, and visualize the process to strengthen your recursion skills with strings.

We'll cover the following...

Solution: Using Recursion

Python 3.5
def recursiveLength(testVariable) :
# Base Case
if (testVariable == "") :
return 0
# Recursive Case
else :
return 1 + recursiveLength(testVariable[1:])
# Driver Code
testVariable = "Educative"
print (recursiveLength(testVariable))

Explanation

The base case for this solution will test for an empty string "". If the string is empty we return 00.

For the recursive case, we call another instance of the same function, but we remove the first element. When the child element returns the length, we add 11 to the returned length.

The recursive case is based on the paradigm that the length of the complete string is 11 ...