C# 中奇妙的函數(shù)–8. String Remove() 和 Replace()
當(dāng)對字符串進(jìn)行操作時,我們經(jīng)常要刪除或者是替換一部分子字符串。 Remove() 和 Replace() 兩個函數(shù)在這種情況就派上用場了。
Remove() – 刪除一部分子字符串
我們都知道 substring 可以返回字符串的一部分。 當(dāng)我們想保留字符串中的一部分substring丟棄其它部分時,就可以使用substring,當(dāng)我們想刪除字符串的一部分并保留其它部分時,就使用Remove。
Remove 有兩種形式:
- Remove(int startIndex)
- 刪除此字符串中從指定位置到最后位置的所有字符。
- Remove(int startIndex, int length)
- 從此實例中的指定位置開始刪除指定數(shù)目的字符。
Remove 會進(jìn)行區(qū)域的檢查,
對于第一種形式 當(dāng)
1. startIndex 小于零 或
2. startIndex 指定的位置不在此字符串內(nèi);
對于第二種形式當(dāng)
1. startIndex 或 count 小于零 或
2. startIndex 加 count 之和指定一個此實例外的位置。
會拋出異常。
在Remove() 和 substring()兩者中,選擇哪一個應(yīng)該是很容易的,看下面的實例:
string test = "Now is the time for all good men to come to the aid of their country.";
// 取頭 10 個字符
var sliceUsingSubstring = test.Substring(0, 10);
// 刪除第10個字符后的所有字符
var sliceUsingRemove = test.Remove(10);
string test = "Now is the time for all good men to come to the aid of their country.";
// 獲取從 length - 10 到最后的部分.
var sliceUsingSubstring = test.Substring(test.Length - 10);
// 刪除從頭到 length - 10, 其余留下
var sliceUsingRemove = test.Remove(0, test.Length - 10);
在這種情況下,substring 看上去更加的簡潔了。
現(xiàn)在看來,它們的確是八斤八兩,但是.net 在這一類的情況下提供了兩種方式,可以完全憑你的喜好來使用。
但是當(dāng)我們要保留或者刪除字符串中間一段時,就可以看出它們的不同了:
// 取從第 10 個開始長度為 10 的子串
var sliceUsingSubstring = test.Substring(10, 10);
// 刪除從第20個字符之后的部分, 再刪除頭 10個
var sliceUsingRemove = test.Remove(20).Remove(0, 10);
在這種情況下,很明顯substring簡便易讀,而且只需要一次操作。
但是如果我們想要刪除中間的一段字符串:
// 取從0開始,長度為10的子串, 再取從第20 開始到末尾的部分
var sliceUsingSubstring = test.Substring(0, 10) + test.Substring(20);
// 從第10開始刪除 10 個字符
var sliceUsingRemove = test.Remove(10, 10);
當(dāng)使用于這種情況時, remove 明顯更簡單,更易讀。
Replace() – 替換 char 或 String
將此實例中的指定 Unicode 字符或 String 的所有匹配項替換為其他指定的 Unicode 字符或 String。
兩種重載的形式
- Replace(char oldChar, char newChar)
將此實例中的指定 Unicode 字符的所有匹配項替換為其他指定的 Unicode 字符。
Replace(string oldValue, string newValue)
將此實例中的指定 String 的所有匹配項替換為其他指定的 String。
string test = "Now is the time for all good men to come to the aid of their country.";
var politicallyCorrect = test.Replace("men", "people");
var spacesToPipes = test.Replace(' ', '|');
var withoutThe = test.Replace("the ", string.Empty);
下一個例子是當(dāng)你有一塊數(shù)據(jù)包含 “<BR/>” HTML 的代碼時,想將它換成 Environment.NewLine:
string test = "Some data & markup was loaded from a data source.<BR/> Oh look, we started a new line!";
var cleansedData = test.Replace("<BR/>", Environment.NewLine);
var moreCleansedData = test.Replace("&", "&")
.Replace(" ", " ")
.Replace("<BR/>", Environment.NewLine);
同時我對stringbuilder進(jìn)行了相同的實驗,發(fā)現(xiàn)在這種情況下stringbuilder 的運行速度非常的緩慢:
var morePerformantCleansedData = new StringBuilder(test)
.Replace("&", "&")
.Replace(" ", " ")
.Replace("<BR/>", Environment.NewLine)
.ToString();
更多精彩的相關(guān)文章,請閱讀喜樂的ASP.NET(Alex Song)
參考翻譯自 C#/.NET Little Wonders: The String Remove() and Replace() Methods

浙公網(wǎng)安備 33010602011771號