2016-12-07 163 views
2

的第二部分,我會一直像這樣的字符串:提取字符串

"/FirstWord/ImportantWord/ThirdWord" 

我怎樣才能提取ImportantWord?話最多隻能包含一個空間,他們被forward slash分離像我把上面,例如:

"/Folder/Second Folder/Content" 
"/Main folder/Important/Other Content" 

我總是希望得到第二個字(Second FolderImportant考慮到上面的例子)

+2

使用[String.Split()](https://msdn.microsoft.com/en-us/library/system.string.split(V =創建一個由'/'字符分割的數組數組 –

回答

3

怎麼樣這個:

string ImportantWord = path.Split('/')[2]; // Index 2 will give the required word 
+2

這將返回''FirstWord「'不''ImportantWord」',因爲數組中的第一項是一個empy字符串(' RemoveEmptyEntries'選項是必需的) –

+0

已更新。謝謝。 – JerryGoyal

1

有幾種方法可以解決這個問題。最簡單的一種是採用String.split

Char delimiter = '/'; 
String[] substrings = value.Split(delimiter); 
String secondWord = substrings[1]; 

(您可能需要做一些輸入檢查,以確保輸入的是正確的格式,否則你會得到一些例外)

另一種方法是使用regex時該模式是簡單/

如果您確信這是一個路徑,你可以使用其他的答案在這裏提到

2

我希望你不需要使用String.Split選項eith呃與特定的字符或一些正則表達式。由於輸入是指向目錄的合格路徑,因此可以使用System.IO.Directory類的Directory.GetParent方法,它將爲父目錄提供DirectoryInfo。從那裏你可以把目錄的名稱,這將是必需的文本。如果你需要在另一個層面上獲得名字的方法Directory.GetParent可以嵌套:

你可以使用這樣的:

string pathFirst = "/Folder/Second Folder/Content"; 
string pathSecond = "/Main folder/Important/Other Content"; 

string reqWord1 = Directory.GetParent(pathFirst).Name; // will give you Second Folder 
string reqWord2 = Directory.GetParent(pathSecond).Name; // will give you Important 

附加說明。

2

你也可以試試這個:

var stringValue = "/FirstWord/ImportantWord/ThirdWord"; 
var item = stringValue.Split('/').Skip(2).First(); //item: ImportantWord