2013-07-12 31 views
0

有沒有比使用substring()更簡單,更簡單的方法?我試圖讓它減少錯誤,因爲輸入LastIndexOf和Length以及計數器時很容易出錯。替代使用子字符串?子字符串使得在輸入時很容易出現重複錯誤

string filepath = "c:\folder1\folder2\folder3\file1.jpg"; 
string file = ""; 

file = filepath.SubString(
    (filepath.LastIndexOf("\\")+1), 
    (filepath.Length - filepath.LastIndexOf("\\")+1) 
); 

我想得到這個值「file1.jpg」。

謝謝...

回答

5

是使用Path.GetFileName

string filepath = "c:\folder1\folder2\folder3\file1.jpg"; 
string file = Path.GetFileName(filePath); 

基於非路徑記錄的另一個選項是使用String.Split函數。

string longString = "The cat jump over the brown fox"; 
string[] splitString = longString.Split(new char[] {' '}); //Splits the string in to array elements wherever it see a space; 
string lastWord = splitString[splitString.Length - 1]; //Could throw a error is the length is less than 1 
string lastTwoWords = String.Join(" ", splitString.Skip(splitString.Length - 2)); //Could throw a error if the length is less than 2 
+0

整潔!還有一個問題。如果它是一個字符串「貓跳過棕色狐狸」,我想要得到這個「棕色狐狸」會怎麼樣?有沒有辦法做到這一點? – fletchsod

+0

看到我的更新,它首先將它分解爲一個數組,然後獲取最後一個單詞和最後兩個單詞。 –

相關問題