public class StringTester { // Develops and tests a few common string manipulation methods. // Exercises the String class methods and the idea of recursion. static String readText(String fileName) { // read an entire text file, concatenate the lines together // to form one long string and return that string. Adds an // extra blank between lines, and uses pseudoKeyboard class. pseudoKeyboard k = new pseudoKeyboard(fileName); String temp = ""; String line = k.readString(); // a single line of text while (!k.eof()) { temp = temp + line + " "; line = k.readString(); } return temp; } static String nextWord (String s, int i) { // returns the next word in the text s, beginning at positon i, // passing over blanks. If no next word in s, return "" while (i < s.length() && s.charAt(i) == ' ') i = i + 1; // pass over leading blanks // now i is at the beginning of the word, or else there // is no next word in s. if (i >= s.length()) return ""; else // end of the word is at the blank that trails it return s.substring(i, s.indexOf(" ", i)); } static void displayWords (String s) { // Display all the words in a string, one word per line. // Use nextWord. Assumes no extra blanks between words int i = 0; // i marks the beginning of a word in s String t = nextWord(s, i); while ( !t.equals("") ) { System.out.println(t); i = i + t.length() + 1; t = nextWord(s, i); } } static String deleteExtraBlanks (String s) { // returns the result of deleting all but one blank between each // pair of words in s, as well as leading and trailing blanks int i = s.indexOf(" "); while (i >= 0) { // squeeze out one blank at a time s = s.substring(0, i) + s.substring(i + 1); i = s.indexOf(" "); } return s; } static String deleteExtraBlanks (String s, int from) { // recursive version int i = s.indexOf(" ", from); // find a pair of blanks if (i < 0) // base case -- none there return s; else // recursive case; delete one return s.substring(0, i) + deleteExtraBlanks(s, i + 1); } static int countWords (String s) { // recursively counts the number of words in a string. Assumes // there is exactly one blank between adjacent words. String t = nextWord(s, 0); // find the next word if (t.equals("")) // base case -- none there return 0; else // recursive case; count it return 1 + countWords(s.substring(t.length() + 1)); } public static void main (String[] argv) { String fileName; // Locate a text with the user's help and read it System.out.println("Enter the name of a text file: "); fileName = Keyboard.readString(); String s = readText(fileName); // display the text in 60-character lines System.out.println("\nOriginal text in 60-character chunks:"); for (int i=0; i