Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Scanner;
- public class withoutString {
- public static void main(String[] args) {
- // Gets base and remove strings
- Scanner input = new Scanner(System.in);
- System.out.print("Enter a Base String: ");
- String base = input.nextLine();
- System.out.print("Enter a Remove String: ");
- String remove = input.nextLine();
- input.close();
- // Informs user of Original Base String and Remove Substring before process starts
- System.out.println("\nBase String: " + base);
- System.out.println("Remove String: " + remove + "\n");
- // Defines necessary variables
- boolean notFinished = true;
- String newBase = "";
- // While loop runs until all instances of the Remove Substring are deleted from the Base string
- // NOTE: This includes the edge case where Base: "heerere" Remove: "ere" -> NewBase: "h"
- while(notFinished){
- // Runs method to delete a first instance of the remove substring. A new base is returned
- newBase = findAndRemove(base, remove);
- if(newBase.equals(base)){
- // If base has changed, we repeat the process encase a new instance
- // of the Remove Substring was produced in the New Base
- notFinished = false;
- }else{
- // If not, we can be sure there is no remaining instance of the Remove Substring
- // and we can terminate the loop
- base = newBase;
- }
- }
- // Output Final Base with no instance of the Remove Substring
- System.out.println("New Base: " + base);
- }
- /*
- Method returns a new Base of type String, after a linear search has removed any
- instances of the remove substring.
- */
- public static String findAndRemove(String base, String remove){
- // Define necessary variables
- String potentialRemove = "";
- String beforeRemove, afterRemove, newBase;
- String baseLower = base.toLowerCase();
- String removeLower = remove.toLowerCase();
- // Linear searches Base for first character of Remove. This will locate any potential Remove instances
- for(int i=0; i<=baseLower.length()-remove.length(); i++){
- if(baseLower.charAt(i) == removeLower.charAt(0)){
- // Potential remove substring located
- potentialRemove = baseLower.substring(i, i+remove.length());
- if(potentialRemove.equals(remove)){
- // If this is a correctly identified remove instance;
- // - Create a Base Substring before the Remove Instance
- beforeRemove = base.substring(0, i);
- // - Create a Base Substring after the Remove Instance
- afterRemove = base.substring(i+remove.length());
- // - Create a new Base using the two substrings, removing the Remove Instance
- newBase = beforeRemove + afterRemove;
- // - Returns the new Base String
- return newBase;
- }
- }
- }
- return base;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement