Java:从 StringBuilder 中删除字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21408401/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 08:32:51  来源:igfitidea点击:

Java: Remove String from StringBuilder

javastringstringbuilder

提问by user2341387

I want to remove String from StringBuilder

我想从 StringBuilder 中删除 String

Example

例子

String aaa = "sample";
String bbb = "sample2";
String ccc = "sample3";

In another part

在另一部分

StringBuilder ddd = new StringBuilder();
ddd.append(aaa);
ddd.append(bbb);
ddd.append(ccc);

I want to check if StringBuilder ddd contains String aaa and remove it

我想检查 StringBuilder ddd 是否包含 String aaa 并将其删除

if (ddd.toString().contains(aaa)) {
    //Remove String aaa from StringBuilder ddd
}

Is that possible? Or is there any other way to do like that?

那可能吗?或者有没有其他方法可以做到这一点?

采纳答案by Evgeniy Dorofeev

try this

尝试这个

    int i = ddd.indexOf(aaa);
    if (i != -1) {
        ddd.delete(i, i + aaa.length());
    }

回答by Salah

It can be done by :

可以通过以下方式完成:

ddd.delete(from, to);

回答by grexter89

try this

尝试这个

public void delete(StringBuilder sb, String s) {
    int start = sb.indexOf(s);
    if(start < 0)
        return;

    sb.delete(start, start + s.length());
}

回答by Fco P.

Create a string from ddd and use replace().

从 ddd 创建一个字符串并使用 replace()。

ddd.toString().replace(aaa,"");