简体   繁体   English

Java-删除字符串的中间部分

[英]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. 您的StringBuilder未使用输入的String初始化。 It should be StringBuilder sb = new StringBuilder(str); 应该是StringBuilder sb = new StringBuilder(str); As such, it is always empty. 因此,它始终为空。
  • substring and delete methods work with the last index exclusive, not inclusive. substringdelete方法与最后一个索引互斥(不包含)一起使用。 So to take a substring of length 3 starting at index 1, you need to call str.substring(1, 4) . 因此,要获取从索引1开始的长度为3的子字符串,您需要调用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). 旁注:由于您仅在一种情况下使用StringBuilder ,因此可以将else if声明移到else if (这样,当String少于3个字符时,您将不会创建无用的对象)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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