![](/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.