MrTunaDeluxe
MrTunaDeluxe

Reputation: 152

Inserting a string between certain characters in another string

Say I have a string, say String stringy = "<Monkey><Banana><Raffle/>"

and another string String stringier = <Cool stuff to add/>

How can I insert stringier between the closing > of <Banana> and the opening < of <Raffle/>? I can't use the index of the string either, because stringy could have more or less characters before the <Raffle/> and will likely never be the same thing. Any ideas?

Upvotes: 0

Views: 130

Answers (4)

Jared Beekman
Jared Beekman

Reputation: 320

Java strings are immutable, but StringBuilder is not.

public class StringyThingy {
  public static void main(String[] args) {
    StringBuilder stringy = new StringBuilder("<Monkey><Banana><Raffle/>");

    System.out.println(stringy);

    // there has to be a more elegant way to find the index, but I'm busy.
    stringy.insert(stringy.indexOf("Banana")+"Banana".length()+1,"<Cool stuff to add/>");

    System.out.println(stringy);
  }
}

// output
<Monkey><Banana><Raffle/>
<Monkey><Banana><Cool stuff to add/><Raffle/>

Upvotes: 0

Sloppy
Sloppy

Reputation: 143

You can use String.indexOf to find an occurrence of a string within another string. So, maybe it would look something like this.

    String stringy = "<Monkey><Banana><Raffle/>";
    String stringier = "<Cool stuff to add/>";

    String placeToAdd = "<Banana><Raffle/>";
    String addAfter = "<Banana>";
    int temp;

    temp = stringy.indexOf(placeToAdd);
    if(temp != -1){
        temp = temp+addAfter.length();

        stringy = stringy.substring(0, temp) + stringier + stringy.substring(temp+1, stringy.length());

        System.out.println(stringy);
    } else {
        System.out.println("Stringier \'" + stringier+"\" not found");
    }

After looking at other answers, replace is probably a better option than the substring stuff.

Upvotes: 0

darijan
darijan

Reputation: 9775

This can be another option:

stringy = stringy.substring(0, stringy.indexOf("<Banana>") + "<Banana>".length()) 
      + stringier 
      + stringy.substring(stringy.indexOf("<Banana>") + "<Banana>".length());

Upvotes: 0

Dan Grahn
Dan Grahn

Reputation: 9414

Are you just looking for a find and replace? If not, can you expand on your question?

stringy = stringy.replace("<Banana><Raffle/>", "<Banana>"+ stringier +"<Raffle/>")

Upvotes: 3

Related Questions