Write a recursive method length that takes a
String and returns its length without calling the
length() method. Think about your base case (what is the
smallest problem) and then think about how to recurse toward that base
case and how to combine the answer you get from the recursive call with
what you know in the current call.
Write a recursive method countXs that takes a
String and returns the number of 'x'
characters it contains.
Write a recursive method countVowels that takes a
String and returns the number of vowels it contains, in
either case. Use the provided isVowel.
Write a recursive method reverse that takes a
String and returns a new String with the same
characters in the opposite order. Hint: the reverse of a string is the
reverse of the rest of it, followed by its first character.
Write a recursive method disemvowel that takes a
String and returns a new String consisting of
the original with all the vowels removed:
disemvowel("recursion") is "rcrsn". Use the
provided isVowel.
Write a recursive method isPalindrome that takes a
String and returns a boolean indicating
whether it reads the same forward and backward, like
"racecar" or "abba". The empty string and any
one-character string are palindromes. Hint: a longer string is a
palindrome if its first and last characters match and what’s between
them is a palindrome.
Write a recursive method indexOf that takes a
String and a char and returns the index of
the first occurrence of the character in the string, or -1
if it doesn’t occur—without calling String’s own
indexOf. Hint: if the character is first, the answer is
0. Otherwise find it in the rest of the string and think
about what that answer tells you.
Write a recursive method repeat that takes a
String and an int n and returns
the string repeated n times: repeat("ab", 3)
is "ababab" and repeat("ab", 0) is
"". Here the recursion is on the number, not the string.
Write a recursive method squeeze that takes a
String and returns a new String in which every
run of the same character repeated is collapsed to a single copy:
squeeze("aaabccd") is "abcd". Hint: compare
the first character to the one after it.
Recursion over strings. Every method here is written the same way: a base
case for the empty string (or a very short one), and a recursive case that
does something with the first character and the answer for the rest of the
string. The starter code provides helpers for taking a string apart:
first(s) returns the first character, rest(s)
returns everything after it, and isVowel(c) says whether a
character is a vowel. You may also use isEmpty(),
charAt, and substring from the
String class.
Strings are a nice place to do recursion because, unlike lists, it’s easy
to build up a new one: first(s) + rest(s) is a new string.
Several of these methods build their answer that way. No loops and no
streams; the point is the recursion. And no reaching for the library
method that already does the job.