1

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?

2 Answers 2

5

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

and

lastIndexOf

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks man....I thought the lastIndexOf returns the last index of the same occurrence...overlooked that part...Thanks...
1

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);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.