14

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.

hamed
  • 7,939
  • 15
  • 60
  • 114
  • 2
    Note: Use `\\.`, as `.` has special meaning in regex (what `split` expects). – Maroun Jan 04 '15 at 09:00
  • If you only need the last dot, find it with `lastIndexOf` and then use `substring` instead of splitting the all string. – Alexis C. Jan 04 '15 at 09:01

2 Answers2

24

Try substring with lastIndexOf method of String:

String str = "almas.test.tst";
System.out.println(str.substring(str.lastIndexOf(".") + 1));
Output:
tst
SMA
  • 36,381
  • 8
  • 49
  • 73
  • `fails for input without "." do remember to test if lastIndexOf(".") != -1` – Anil Muppalla Feb 28 '18 at 03:14
  • 3
    @AnilMuppalla actually, it doesn't fail but rather return the whole word, as expected when not finding the delimiter. `System.out.println("no-dots-whatsoever".substring("no-dots-whatsoever".lastIndexOf(".") + 1)); -->no-dots-whatsoever` – akapulko2020 Apr 24 '18 at 10:03
5

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);
dReAmEr
  • 6,986
  • 7
  • 36
  • 63