简体   繁体   English

Java String.indexOf API

[英]Java String.indexOf API

I have following situation, 我有以下情况

String a="<em>crawler</em> <em> Yeahhhhh </em></a></h3><table";
System.out.println(a.indexOf("</em>"));

It returns the 11 as the result which was the first that it founds. 它返回结果11,这是它找到的第一个结果。

Is there any way to detect the last instead of the first one for the code written above? 有什么方法可以检测上面编写的代码的最后一个而不是第一个?

lastIndexOf gives you the index of the last occurrence of needle in the haystack , but the following example of finding all occurrences may also be instructive: lastIndexOf给你最后一次出现的索引needlehaystack ,但要找到所有出现也可能是有益的下面的例子:

for (int pos = -1; (pos = haystack.indexOf(needle, pos + 1)) != -1;) {
    System.out.println(pos);
}

To find all occurrences backward , you do the following: 向后查找所有出现,你做到以下几点:

for (int pos = haystack.length(); (pos = haystack.lastIndexOf(needle, pos - 1)) != -1;) {
    System.out.println(pos);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM