I've been googling around and trying to find out what is the behaviour of lastIndexOf, but can't really find the answer to it...
I have a potentially large string that I need to search, and I'm 99% positive that a tag, ex: </data>
will be at the end of it. I am trying to strip that off and append some extra data to the string and then close it off again after.
Right now I'm using indexOf, but performance is my top priority here, so I was thinking of using lastIndexOf...
Could some expert with Java confirm whether lastIndexOf would search from the back of the string?
Example:
xml = xml.substring(0, xml.lastIndexOf("</data>"));
xml+"<mystuff>hello world</mysruff>";
xml+"</data>";
From the JavaDoc:
int lastIndexOf(String str, int fromIndex) Returns the index within this string of the last occurrence of the specified substring, searching backward starting at the specified index.
Based on the source found here, it appears as if lastIndexOf
does traverse from the end of the string, towards the beginning. An excerpt is posted below for convenience; note the decrement operations as it is keeping track of i
and j
to find the last match.
startSearchForLastChar: while (true) {
while (i >= min && source[i] != strLastChar) {
i--;
}
if (i < min) {
return -1;
}
int j = i - 1;
int start = j - (targetCount - 1);
int k = strLastIndex - 1;
while (j > start) {
if (source[j--] != target[k--]) {
i--;
continue startSearchForLastChar;
}
}
return start - sourceOffset + 1;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With