简体   繁体   中英

Substring part of a string

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.

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)

use String#lastIndexOf()

"/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());

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM