Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - remove middle part of a string

Tags:

java

I want the following output for the following input:

input: adele
output: ae

Code:

public class delDel {
    public static String delDel(String str) {
        StringBuilder sb = new StringBuilder();
        if(str.length() < 3){
           return str;
        }
        else if(str.substring(1, 3).equals("del")){
            StringBuilder afterRemove = sb.delete(1, 3);
            return afterRemove.toString();
        }
        else{
           return str;
        }

   }

   public static void main(String[] args) {
      Scanner input = new Scanner(System.in);

      String yourStr = input.nextLine();

      System.out.println(delDel(yourStr));
   }
}

But I keep getting the same input.

like image 620
test player Avatar asked Sep 15 '26 19:09

test player


1 Answers

There are multiple problems here:

  • Your StringBuilder isn't initialized with the input String. It should be StringBuilder sb = new StringBuilder(str); As such, it is always empty.
  • substring and delete methods work with the last index exclusive, not inclusive. So to take a substring of length 3 starting at index 1, you need to call str.substring(1, 4).

Corrected code:

public static String delDel(String str) {
    StringBuilder sb = new StringBuilder(str);
    if(str.length() < 3){
       return str;
    }
    else if(str.substring(1, 4).equals("del")){
        StringBuilder afterRemove = sb.delete(1, 4);
        return afterRemove.toString();
    }
    else{
       return str;
    }
}

Side-note: since you are only using the StringBuilder in one case, you could move its declaration inside the else if (this way, you won't create a useless object when the String is less than 3 characters).

like image 126
Tunaki Avatar answered Sep 17 '26 07:09

Tunaki