14

I want to remove String from StringBuilder

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

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

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

user2341387
  • 303
  • 1
  • 5
  • 14
  • 2
    Take a look at [this question](http://stackoverflow.com/a/12353395/3227787). – Bruno Toffolo Jan 28 '14 at 14:32
  • 2
    Why add it in the first place? I'm assuming this is a very contrived sample: why can't you add a check to whatever condition it is before adding `aaa`? – Jeroen Vannevel Jan 28 '14 at 14:33
  • @devnull. This is not exactly a duplicate, although close. – Mad Physicist Jan 28 '14 at 14:39
  • @JeroenVannevel. Not necessarily contrived. A StringBuilder can be created from a pre-existing string or other source. Removing bits of it may not be the best way to handle things, as you point out, but it may be the only alternative in some cases. – Mad Physicist Jan 28 '14 at 14:41

4 Answers4

12

try this

    int i = ddd.indexOf(aaa);
    if (i != -1) {
        ddd.delete(i, i + aaa.length());
    }
Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
  • 1
    You need to do `i + aaa.length()` for the second argument, as [`StringBuilder#delete`](http://docs.oracle.com/javase/7/docs/api/java/lang/StringBuilder.html#delete%28int,%20int%29) takes an `end` index, not a length. – ajp15243 Jan 28 '14 at 14:40
5

try this

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

    sb.delete(start, start + s.length());
}
grexter89
  • 1,091
  • 10
  • 23
2

Create a string from ddd and use replace().

ddd.toString().replace(aaa,"");
Fco P.
  • 2,486
  • 17
  • 20
0

It can be done by :

ddd.delete(from, to);
Salah
  • 8,567
  • 3
  • 26
  • 43