Write a recursive function named lettersOnly that accepts a string s as a parameter and returns a string with the same characters as s, in the same order, but excluding any characters that are not alphabetic letters from A-Z, case-insensitive. For example, the call of lettersOnly("{[[Friends, save $$ with 'Geico'!!]]}") should return "FriendssavewithGeico". If the string passed is empty or contains no letters, return an empty string.

Answer :

Answer:

/*

 * Method to print the letters in a passed in string by recursion. Each

 * recursion compresses the string by excluding the last character one at a time

 */

public static void lettersOnly(String s) {

 //If string is empty, return nothing

 if (s.length() < 1) {

  return;

 }

 

 // Get the last character of the string

 char x = s.charAt(s.length() - 1);

 // Check if the length of the string is 1 or less

 // If it is 1 or less, check if the character is an alphabet

 // A character x is an alphabet if its ASCII representation is

 // between 65 and 90 (both inclusive) for uppercase letters

 // or between 97 and 122 (both inclusive) for lowercase letters

 // To get the ASCII representation, the character is type cast by prepending it

 // with (int) e.g (int) z gives 122

 if ((s == null) || (s.length() <= 1)) {

  if ((((int) x >= 65 && (int) x <= 90)) || ((int) x >= 97 && (int) x <= 122))

   System.out.println(s);

 }

 // else, if the length of the string is more than 1

 else {

  // Get the substring including all the characters in the string except the last

  // character.

  // Recall the function lettersOnly on the substring

  lettersOnly(s.substring(0, s.length() - 1));

  // Check if the last character of the string is an alphabet

  // If it is, print it out.

  if ((((int) x >= 65 && (int) x <= 90)) || ((int) x >= 97 && (int) x <= 122))

   System.out.print(s.charAt(s.length() - 1));

 }

} // End of method

Explanation:

Read through the comments of the code for better readability and understanding. To get a better representation of the code, the source file code has been attached to this response. Please download it and you can run it as a Java application on your machine.

Hope this helps!

${teks-lihat-gambar} stigawithfun

Other Questions