Mr CooL
Mr CooL

Reputation: 1579

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.

Is there any way to detect the last instead of the first one for the code written above?

Upvotes: 1

Views: 1744

Answers (2)

polygenelubricants
polygenelubricants

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

Adriaan Stander
Adriaan Stander

Reputation: 166396

Have a look at indexOf( ) and lastIndexOf( ) in Java

and

lastIndexOf

Upvotes: 5

Related Questions