Reputation: 1477
First, I want to excuse if this problem is already discussed and I'll be glad if you point me to an already answered question! I couldn't find one that will helps me out.
I have to extract only the last part after the last "/" in such a string: /test/test2/test3
I have to extract only the "test3". But I cannot get to a way myself so I'm asking for your help.
Upvotes: 0
Views: 174
Reputation: 404
In case you need to isolate also the other parts of the string, this will be easiest way.
String s="a/b/c"; //Works also for "a b c" and "a/b/c/"
String[] parts=s.split("/");
System.out.println(parts[parts.length-1]);
Upvotes: 2
Reputation: 1503290
You just need to find the last index of /
, and then take the substring after that:
int lastIndex = text.lastIndexOf('/');
String lastPart = text.substring(lastIndex + 1);
(Other options exist, of course - regular expressions and splitting by /
for example... but the above is what I'd do.)
Note that because we've got to use + 1
to get past the last /
, this has the handy property that it still works even if there aren't any slashes:
String text = "no slashes here";
int lastIndex = text.lastIndexOf('/'); // Returns -1
String lastPart = text.substring(lastIndex + 1); // x.substring(0).equals(x)
Upvotes: 15
Reputation: 46428
"/test/test2/test3".substring("/test/test2/test3".lastIndexOf("/")+1)
Also assuming its a file path. you can also use File#getname()
File f = new File("/test/test2/test3");
System.out.println(f.getName());
Upvotes: 10