2013-02-19 82 views
0

首先,如果已經討論過這個問題,我想原諒,如果您指出我已經回答了問題,我會很高興!我找不到能幫助我的人。字符串的子串部分

我在最後一個「/」,在這樣的字符串只提取了最後一部分: /測試/測試2/TEST3

我只提取「TEST3」。但我無法自拔,所以我在尋求你的幫助。

回答

2

如果您還需要隔離字符串的其他部分,這將是最簡單的方法。

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

使用String#lastIndexOf()

"/test/test2/test3".substring("/test/test2/test3".lastIndexOf("/")+1) 

而且假設它的文件路徑。你也可以使用File#getname()

File f = new File("/test/test2/test3"); 
System.out.println(f.getName()); 
+3

該死的,你太快了。 – 2013-02-19 20:58:53

+0

謝謝! 儘管我無法使用它,因爲我不知道最後一個「/」之前的前一個字符串。我很感謝你的快速回答! :) – Seishin 2013-02-19 21:05:33

15

你只需要找到last index of/,然後取後,該substring

int lastIndex = text.lastIndexOf('/'); 
String lastPart = text.substring(lastIndex + 1); 

(其他選項存在,當然 - 正則表達式和分裂的/例如...但上面是我會做的。)

請注意,因爲我們必須使用+ 1來通過最後/,這有它仍然有效,即使有沒有任何斜線的方便特性:

String text = "no slashes here"; 
int lastIndex = text.lastIndexOf('/'); // Returns -1 
String lastPart = text.substring(lastIndex + 1); // x.substring(0).equals(x) 
+0

非常感謝! 你的答案幫我解決了! :) – Seishin 2013-02-19 21:06:00