简体   繁体   中英

Java - remove middle part of a string

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.

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM