How to get 4th last occurence in a string

L

loial

In the following string I want to find the psotion of the next to last
occurrence of "/" so that I can set a variable to "656/8888"


/10000/20000/656/8888


Can lastindexOf do this?
 
S

Stefan Rybacki

loial said:
In the following string I want to find the psotion of the next to last
occurrence of "/" so that I can set a variable to "656/8888"


/10000/20000/656/8888


Can lastindexOf do this?

Obviously not. It is called LASTindexOf for a reason. So first things first, do
you want to get the 4th or second to last occurrence? If second to last you know
at least one way to do it if you think algoritmic, do you? One hint. What do you
get when you get the last index and then get the last index again on the string
that is bounded by the previous last index?

Stefan
 
P

Patricia Shanahan

Eric said:
Not directly. You could use lastIndexOf on the original
string to find the rightmost slash, and use it again on the
substring that ends just before that slash:

String str = "10000/20000/656/8888";
String tail = null;
int i = str.lastIndexOf('/');
if (i >= 0) {
i = str.substring(0, i).lastIndexOf('/');
if (i >= 0)
tail = str.substring(i + 1);
}

You can simplify this code a little bit because lastIndexOf has an
alternative form that searches backwards from a specified index.

Patricia
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,009
Latest member
GidgetGamb

Latest Threads

Top