CSC223 Exam2 Part 2 Spring 2018 Name Problem 1- Recursion -22 Create a class cal
ID: 3723868 • Letter: C
Question
CSC223 Exam2 Part 2 Spring 2018 Name Problem 1- Recursion -22 Create a class called Recursive Replace with a method called replace. Method replace will have functionality similar to the replace method in class String in the Java APl. Method replace will substitute all instances of one character by another. Your replace method will have 3 parameters: the string, the character to be replaced, and the new character. Your replace method will return a new String with the appropriate characters replaced Method replace must evaluate each character in the string and replace as necessary. This will be accomplished through successive calls to method replace. I have provided for you a class called TestReplace to test your replace method. Do not make any changes to TestReplace. Your RecursiveReplace class should work with TestReplace. Deliverable: The Exam sheet Printout of your source code with any output included as a comment at the end of your RecursiveReplace class. Digital copy of your source code. Place a copy of your NetBeans src folder in a folder "your last name" 1. 2. 3. entitled A class to test the recursive string replace. public class TestReplace public static void main(String args) testReplace(); public static void testReplace() RecursiveStringReplace rs new RecursiveStringReplace(): String result; //TEST STRINGS String s1 String s2-"c" String s3 "a String s4 = "ABC cdefgh"; String s5 "ABC bcadefgah" String s6 = "adad ";
Explanation / Answer
public class RecursiveStringReplace
{
public String replace(String s, char from, char to)
{
if(s.length() < 1) { return s; }
char first = from == s.charAt(0) ? to: s.charAt(0);
return first + replace(s.substring(1), from, to);
}
}