简体   繁体   English

Java解析字符串的最后一部分

[英]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 - , ie 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). 我尝试通过使所有字符从字符串末尾直到-5 ,但这并不总是有效的(如果数字大于1的整数)。 lastStateVisited is my string lastStateVisited是我的字符串

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 谢谢

Try this: 尝试这个:

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

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. 那么,为什么不首先获取last的索引-出现在字符串中。 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. reqStr包含必需的字符串。 You can use loop with this part of code to extract more such strings. 您可以在这部分代码中使用循环,以提取更多此类字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM