Replace a String between two Strings

前端 未结 6 1938
说谎
说谎 2020-12-07 00:32

Let\'s say we have something like:

&firstString=someText&endString=OtherText

And I would like to replace \"someText\" with somethin

6条回答
  •  孤街浪徒
    2020-12-07 01:16

    This solution checks that we're not going of the end of the string and will do it for multiple occurrences.

     int startIndex = text.indexOf(startDelim);
     while (startIndex > -1)
     {
        int endIndex = text.indexOf(endDelim, startIndex);
        String endPart = "";
    
        if ((endIndex + endDelim.length()) < text.length())
           endPart = text.substring(endIndex + endDelim.length());
    
        text = text.substring(0, startIndex) + replacementText + endPart;
        startIndex = text.indexOf(startDelim);
     }
    

提交回复
热议问题