Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does lastIndexOf in Java search from end of String?

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>";
like image 377
codenamezero Avatar asked Nov 16 '11 21:11

codenamezero


2 Answers

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.

like image 53
Guildencrantz Avatar answered Sep 21 '22 01:09

Guildencrantz


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;
}
like image 28
Jon Newmuis Avatar answered Sep 23 '22 01:09

Jon Newmuis