2013-04-07 103 views
17

我有有如下格式的目錄字符串:獲取內容

C:// //你好世界

我將如何提取的最後一個/字符後的所有(世界)?

回答

27
string path = "C://hello//world"; 
int pos = path.LastIndexOf("/") + 1; 
Console.WriteLine(path.Substring(pos, path.Length - pos)); // prints "world" 

LastIndexOf方法執行相同IndexOf ..但是從字符串的結尾。

3

我會建議看看System.IO命名空間,因爲它似乎你可能想要使用它。還有DirectoryInfo和FileInfo也可以在這裏使用。具體DirectoryInfo's Name property

var directoryName = new DirectoryInfo(path).Name; 
9

有與路徑稱爲Path工作靜態類。

您可以通過Path.GetFileName獲取完整的文件名。

你可以得到的文件名不帶擴展名與Path.GetFileNameWithoutExtension

+1

我曾經想過,但要注意的是,OP似乎不把重點放在一個文件,而是一個目錄 – 2013-04-07 02:51:23

9

using System.Linq;

var s = "C://hello//world"; 
var last = s.Split('/').Last(); 
1

試試這個:

string worldWithPath = "C://hello//world"; 
string world = worldWithPath.Substring(worldWithPath.LastIndexOf("/") + 1); 
+1

這是相同的解決方案已經由Simon Whitehead(http://stackoverflow.com/a/15857606/2029849)發佈,除了'Substring'方法調用中明確給定的長度之外。 – abto 2017-01-14 14:07:07

+0

這是更聰明的解決方案,而不是@abto – Lali 2017-12-28 10:15:35