![](/img/trans.png)
[英]Extracting integers from a string and store them in separate variables in java with substring and lastIndexOf(“ ”) methods
[英]Does lastIndexOf in Java search from end of String?
我一直在谷歌上搜索並試圖找出lastIndexOf的行為,但無法真正找到它的答案......
我有一個可能需要搜索的大字符串,而且我肯定99%肯定標簽,例如: </data>
將在它的末尾。 我試圖剝離它並將一些額外的數據附加到字符串,然后再關閉它。
現在我正在使用indexOf,但性能是我的首要任務,所以我在考慮使用lastIndexOf ......
一些Java專家可以確認lastIndexOf是否會從字符串的后面進行搜索?
例:
xml = xml.substring(0, xml.lastIndexOf("</data>"));
xml+"<mystuff>hello world</mysruff>";
xml+"</data>";
來自JavaDoc :
int lastIndexOf(String str,int fromIndex)返回指定子字符串最后一次出現的字符串中的索引,從指定的索引開始向后搜索。
基於此處找到的源 ,看起來好像lastIndexOf
從字符串的末尾開始遍歷。 為方便起見,下面張貼了一段摘錄; 注意減量操作,因為它跟蹤i
和j
以找到最后一個匹配。
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;
}
來自Javadoc :
返回指定字符最后一次出現的字符串中的索引。 對於ch在0到0xFFFF(包括)范圍內的值,返回的索引(以Unicode代碼為單位)是最大值k,這樣:
this.charAt(k) == ch
是真的。 對於ch的其他值,它是最大值k,使得:
this.codePointAt(k) == ch
是真的。 在任何一種情況下,如果此字符串中沒有出現此類字符,則返回-1。 從最后一個字符開始向后搜索字符串。
是的,確實如此。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.