Question

Question 2. Consider a recursive method that removes all occurrences of substring in a given string...

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’

  1. Write a complete pseudo code/algorithm to solve the requirement of the method as explained above. (15 points)

Note: write the information that you need to describe the header of the method

  1. Trace your algorithm using input1. (5 points)

Homework Answers

Answer #1

Short Summary:

  • Given you pesuedo code and program code together and shown you the sample runs

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!!!

**************************************************************************************

Know the answer?
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for?
Ask your own homework help question
Similar Questions
ADVERTISEMENT
Need Online Homework Help?

Get Answers For Free
Most questions answered within 1 hours.

Ask a Question
ADVERTISEMENT