Question: Java Recursion, solving a string problem In this task, you are required to write a recursion that gets a string and two characters and returns
Java Recursion, solving a string problem
In this task, you are required to write a recursion that gets a string and two characters and returns the substring that is enclosed in two given characters. You can assume that the given string includes only one instance of each enclosing characters. For example, where the input string is This is [quite} an example! and the first enclosing character is '[' and the second is '}', it should return quite. The name of the method is getSubstring and the header of the method was written for you in Lab2.java.
heres by code below
/** * This method returns a substring of the given input string that is enclosed in two * given characters. * @param str is a string that contains at least two characters including open and close * @param open is a character at the beginning of the string that should be returned. * @param close is a character at the end of the string that should be returned. * @return returns a string enclosed in two given characters of open and close . * @pre The given str contains only one open and one close character. */ public static String getSubstring(String str, char open, char close) { //Insert your code here and change the return statement to fit your implementation. if(str.charAt(0) == '(') { return getSubstring(str.substring(0,str.length()-1),open,close); } if(str.charAt(0) == ')'){ return getSubstring(str.substring(0,str.length()-1),open,close); } if(str.charAt(0) == '(' && str.charAt(str.length()-1) == ')') { return getSubstring(str.substring(0,str.length()-1),open,close); } else { return getSubstring(str.substring(0,str.length()-1),open,close); } }
heres the junit testing class using eclipse
@Test public void testGetSubstring1() {
String str1 = "x + y + z - ( y * z) / 3 * n "; String result = " y * z"; char open = '('; char close = ')'; assertEquals("Failed: getSubstring(\"x + y + z - ( y * z) / 3 * n \", \"(\", \")\")", result, Lab2.getSubstring("x + y + z - ( y * z) / 3 * n ", '(', ')')); }
the output should be y*z using recursion. How exactly do i achieve this
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
