Let\'s say we have something like:
&firstString=someText&endString=OtherText
And I would like to replace \"someText\" with somethin
yourString.replace("someText", "somethingElse");
EDIT based on clarification
String x = "&firstString=someText&endString=OtherText";
int firstPos = x.indexOf("&firstString=") + "&firstString=".length();
int lastPos = x.indexOf("&endString", firstPos);
String y = x.substring(0,firstPos) + "Your new text" + x.substring(lastPos);
System.out.println(y);
Output:
&firstString=Your new text&endString=OtherText
You can use String#replaceAll that has support for regex like this:
String newstr = str.replaceAll("(&firstString=)[^&]*(&endString=)", "$1foo$2");
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);
}
The easiest to understand way to do it is to search for the delimiters, and cut out a substring between their positions, like this:
String str = "&firstString=someText&endString=OtherText";
String firstDelim = "&firstString=";
int p1 = str.indexOf(firstDelim);
String lastDelim = "&endString=";
int p2 = str.indexOf(lastDelim, p1); // look after start delimiter
String replacement = "quick_brown_fox";
if (p1 >= 0 && p2 > p1) {
String res = str.substring(0, p1+firstDelim.length())
+ replacement
+ str.substring(p2);
System.out.println(res);
}
just replacing the whole &firstString=someText& since this includes the outer barriers which I assume to be URL related?
As I understood the question, you should do something like this, but I'm not sure I totally got what you asked:
yourString = firstString + replacingString + endString;
If you want the "replaced" string:
replacedString = wholeString.substring(0, wholeString.lastIndexOf(endString) - 1);
replacedString = tempString.substring(firstString.length() + 1);