java java如何从末尾分割字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27763984/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
java how to split string from end
提问by hamed
I have a string like "test.test.test"...".test" and i need to access last "test" word in this string. Note that the number of "test" in the string is unlimited. if java had a method like php explode
function, everything was right, but... . I think splitting from end of string, can solve my problem.
Is there any way to specify direction for split
method?
I know one solution for this problem can be like this:
我有一个像“test.test.test”...“.test”这样的字符串,我需要访问这个字符串中的最后一个“test”字。请注意,字符串中“测试”的数量是无限的。如果 java 有一个像 phpexplode
函数这样的方法,那一切就都对了,但是…… 我认为从字符串末尾拆分可以解决我的问题。有没有办法指定split
方法的方向?我知道这个问题的一个解决方案可能是这样的:
String parts[] = fileName.split(".");
//for all parts, while a parts contain "." character, split a part...
but i think this bad solution.
但我认为这是一个糟糕的解决方案。
回答by SMA
Try substring with lastIndexOf method of String:
使用 String 的 lastIndexOf 方法尝试子字符串:
String str = "almas.test.tst";
System.out.println(str.substring(str.lastIndexOf(".") + 1));
Output:
tst
回答by RE350
I think you can use lastIndexOf(String str)
method for this purpose.
我认为您可以lastIndexOf(String str)
为此目的使用方法。
String str = "test.test.test....test";
int pos = str.lastIndexOf("test");
String result = str.substring(pos);