THINK FIRST·CODE LATER

← All labs

Recursion on strings

Problem

Write RecursiveStrings with five recursive methods — no loops anywhere:

  • reverse(String s);
  • count(String s, char c) — how many times c occurs;
  • countCapitals(String s);
  • removeSpaces(String s);
  • length(String s) — without calling s.length().

Each one follows the same pattern: the empty string is the base case; otherwise deal with the first character and call the method on s.substring(1).

main reads a line of text, then a line whose first character is the letter to count. For the input

Wenzhou Kean University
n

the program prints

Reversed: ytisrevinU naeK uohzneW
Occurrences of 'n': 3
Capital letters: 3
Without spaces: WenzhouKeanUniversity
Length, counted recursively: 23

Data for this lab

Your program reads its data from standard input. Download the file, then give it to your program as shown below. Start with data set 1: its expected output is given.

l17-6-data-1.txt

Wenzhou Kean University
n
What your program must print for l17-6-data-1.txt
Reversed: ytisrevinU naeK uohzneW
Occurrences of 'n': 3
Capital letters: 3
Without spaces: WenzhouKeanUniversity
Length, counted recursively: 23

Run your program first, then open this and compare line by line: your output must contain these lines exactly.

How to give the file to my program

Terminal (macOS, Linux, or Windows Command Prompt), after compiling:

java Main < l17-6-data-1.txt

Windows PowerShell does not understand <:

Get-Content l17-6-data-1.txt | java Main

IntelliJ IDEA: Run → Edit Configurations → Redirect input from. Or simply paste the content of the file into the console when the program waits for input.

Write it here or in your IDE, then paste it. Compile and test it yourself before comparing. Your code stays in your browser — it is never sent to or stored on the server.