Reputation: 1579
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.
Is there any way to detect the last instead of the first one for the code written above?
Upvotes: 1
Views: 1744
Reputation: 383746
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:
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);
}
Upvotes: 1
Reputation: 166396
Have a look at indexOf( ) and lastIndexOf( ) in Java
and
Upvotes: 5