lukas.coenig
lukas.coenig

Reputation: 551

Get next occurrence from RIGHT TO LEFT of a substring in a string (Java)

Say I have a string s like this:

s = "... *begin* - some-code-here - *end* ..."
i:                    ^

and an index i pointing to a position between "*begin*" and "*end*", e.g., to the 'e' of "some".

To get the index of the (next) occurrence of "*end"*, I could use

s.indexOf("*end*", i)

Is there a similar way to get the index of the next "*begin*" to the left?

Upvotes: 2

Views: 801

Answers (2)

Moosa
Moosa

Reputation: 79

I want this answer to add as comment to wero's answer but due to low reputation I am unable to do so.

I think it should be like

s = s.substring(0, i);

s.indexOf("*begin");

Upvotes: 0

wero
wero

Reputation: 32980

Use

s.lastIndexOf("*begin*", i);

Upvotes: 6

Related Questions