Johny
Johny

Reputation: 129

Java parsing last part of a string

I have three strings.

0:0:0-0:0:1
0:0:0-3:0:0-1:2:0
0:0:0-3:0:0-3:2:0-3:2:1

I am trying to do an exercise where I am parsing the string to output only the last part after the -, i.e. respectively:

0:0:1
1:2:0
3:2:1

I have tried of doing it by getting all the characters from the end of the string up until -5, but that won't always work (if the numbers are more then 1 integer). lastStateVisited is my string

lastStateVisited = lastStateVisited.substring(lastStateVisited.length() - 5);

I thought of splitting the string in an array and getting the last element of the array, but it seems inefficient.

String[] result = lastStateVisited.split("[-]");
lastStateVisited = result[result.length - 1];

What is a way I could do this? Thanks

Upvotes: 0

Views: 286

Answers (2)

jack jay
jack jay

Reputation: 2503

Since your requirement concentrate around your need of acquiring the sub-string from the end till - appears first time.

So why not first get the index of last - that appeared in string. And after than extract the sub-string from here till end. Good option. :)

String str = "0:0:0-3:0:0-3:2:0-3:2:1";
String reqStr = str.substring(str.lastIndexOf('-')+1);

reqStr contains the required string. You can use loop with this part of code to extract more such strings.

Upvotes: 0

riadrifai
riadrifai

Reputation: 1168

Try this:

String l = "your-string";
int temp = l.lastIndexOf('-');
String lastPart = l.substring(temp+1);

Upvotes: 2

Related Questions