str.substring(1)
creates a substring that contains all the characters from str
from
character 1 to the end.
public class StringTester { public static int length( String str ) { if ( str.isEmpty() ) return 0; else return 1 + length( str.substring(1) ); } public static void main (String[] args) { String snake = "rattlesnake"; System.out.println( "Length of " + snake + " is: " + length( snake ) ); } }
We now have all the pieces needed to complete the method
Study how length()
fits the recursive definition:
str.substring(1)
is the tail of the string.length( str.substring(1) )
is the length of the tail.
Recall that in Java, the index of the first character of a string is 0, so that the
str.substring(1)
gives you all the characters of the string starting with
the character after the first.
However: if the string has only one character in it, then
str.substring(1)
gives you an empty string.
(So the tail of a one-character string is the empty string.)
In computing the length (11) of the example, how many objects were created by the
length()
method?