hamed
hamed

Reputation: 8043

java how to split string from end

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.

Upvotes: 14

Views: 26954

Answers (2)

dReAmEr
dReAmEr

Reputation: 7196

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);

Upvotes: 5

SMA
SMA

Reputation: 37053

Try substring with lastIndexOf method of String:

String str = "almas.test.tst";
System.out.println(str.substring(str.lastIndexOf(".") + 1));
Output:
tst

Upvotes: 24

Related Questions