Question 2. Consider a recursive method that removes all occurrences of substring in a given string
Examples:
Input1 : str=‘abcccabc’, substr= ‘abc’, result1: ‘cc’
Input2 : str=‘aabcbcc’, substr= ‘abc’, result2: ‘abcc’
Input3 : str=‘bacbcbcc’, substr= ‘ab’, result3: ‘bacbcbcc’
Note: write the information that you need to describe the header of the method
Short Summary:
Source Code:
public class Main {
// Function to remove all occurrences
// of a character in the string
static String removeStringRecursive(String str,
String X, int startIndex)
{
// Base Case
if (str.length() == 0)
{
return "";
}
// Take substring from start index to til the end
String substr = str.substring(startIndex, str.length());
// Check if the substring has the word
int newIndex = substr.indexOf(X);
// If yes
if(newIndex > -1){
// If startIndex and newIndex are same, start the next
iteration with the same index
//if not, move one position forward
if(startIndex != newIndex) {
startIndex++;
}
// Remove the string
substr = substr.replaceFirst(X, "");
// Get the correct string to pass for next
iteration
if(startIndex > 0) {
str = str.substring(0,
startIndex-1) + substr;
}
else {
str = substr;
}
// Return the final string
return removeStringRecursive(str, X, startIndex);
}
else{
return str;
}
}
public static void main(String[] args) {
// Given String
String str = "abcccabc";
System.out.println("Input: " + str);
// Given string to remove
String X = "abc";
System.out.println("substr: " + X);
// Function call
str = removeStringRecursive(str, X, 0);
System.out.println("Output: " + str);
}
}
Sample Run:
Case 1:
Case 2:
Case 3:
**************************************************************************************
Feel free to rate the answer and comment your questions, if you have any.
Please upvote the answer and appreciate our time.
Happy Studying!!!
**************************************************************************************
Get Answers For Free
Most questions answered within 1 hours.