Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java how to split string from end

Tags:

java

string

split

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:

String parts[] = fileName.split(".");
//for all parts, while a parts contain "." character, split a part...

but i think this bad solution.

like image 584
hamed Avatar asked Jan 04 '15 09:01

hamed


Video Answer


2 Answers

Try substring with lastIndexOf method of String:

String str = "almas.test.tst";
System.out.println(str.substring(str.lastIndexOf(".") + 1));
Output:
tst
like image 50
SMA Avatar answered Nov 15 '22 10:11

SMA


I think you can use lastIndexOf(String str) method for this purpose.

String str = "test.test.test....test";

int pos = str.lastIndexOf("test");

String result = str.substring(pos);
like image 23
dReAmEr Avatar answered Nov 15 '22 11:11

dReAmEr