我需要從另一個字符串中刪除第一個(也是唯一的第一個)字符串。C# - 從另一個字符串中刪除第一個子字符串的最簡單方法
以下是替換字符串"\\Iteration"
的示例。這:
ProjectName\\Iteration\\Release1\\Iteration1
會變成這樣:
ProjectName\\Release1\\Iteration1
這裏是一些代碼,這是否:
const string removeString = "\\Iteration";
int index = sourceString.IndexOf(removeString);
int length = removeString.Length;
String startOfString = sourceString.Substring(0, index);
String endOfString = sourceString.Substring(index + length);
String cleanPath = startOfString + endOfString;
這似乎是一個大量的代碼。
所以我的問題是:是否有一個更清潔/更可讀/更簡潔的方式來做到這一點?
對於涉及非ASCII字符的字符串,此答案可能會中斷。例如,在美國文化下,'æ'和'ae'被認爲是平等的。嘗試從'Encyclopædia'中刪除'paedia'將會拋出一個'ArgumentOutOfRangeException',因爲當匹配的子字符串只包含5時你試圖刪除6個字符。 – Douglas 2016-02-18 15:13:43
我們可以這樣修改它:'sourceString.IndexOf(removeString,StringComparison。 Ordinal)'以避免例外。 – 2016-12-20 19:37:57