Does lastIndexOf search Java from end of line?

I searched the searches and tried to figure out what the lastIndexOf behavior is, but cannot find the answer to it ...

I have a potentially large string that I need to look for, and I'm 99% sure that the tag, ex: </data> , will be at the end of it. I am trying to clear this and add additional data to the line, and then close it again after.

I am currently using indexOf, but performance is my top priority, so I was thinking about using lastIndexOf ...

Can any Java expert confirm if lastIndexOf will search on the back of the string?

Example:

 xml = xml.substring(0, xml.lastIndexOf("</data>")); xml+"<mystuff>hello world</mysruff>"; xml+"</data>"; 
+4
source share
3 answers

From JavaDoc :

int lastIndexOf (String str, int fromIndex) Returns the index on this line of the last occurrence of the specified substring, looking back, starting at the specified index.

+10
source

Based on the source found here , it seems that lastIndexOf is moving from the end of the line to the beginning. The shutter speed is set below for convenience; pay attention to decrement operations as it tracks 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; } 
+4
source

From Javadoc :

Returns the index on this line of the last occurrence of the specified character. For ch values ​​ranging from 0 to 0xFFFF (inclusive), the index (in units of Unicode code), which is the largest value of k, such that:

 this.charAt(k) == ch 

truly. For other values ​​of ch, this is the largest value of k such that:

 this.codePointAt(k) == ch 

truly. In any case, if such a character is not found in this line, -1 is returned. The line is executed in the reverse order, starting with the last character.

So yes.

0
source

Source: https://habr.com/ru/post/1381572/


All Articles