[英]C#: How to use the char overload for string.Replace() to replace with nothing?
我有以下擴展方法(無效且不編譯 ATM):
public static string Strip( this string str, char[] charsToStrip )
{
foreach( char c in charsToStrip )
{
str.Replace( c, "" );
}
return str;
}
str.Replace() 調用需要調用 Replace() 的 'char' 重載,但是使用此重載我不確定將什么傳遞給第二個參數以告訴它用“nothing”替換。
此 function 的目標是迭代charsToStrip
變量中的每個字符並刪除源字符串str
中該字符的所有實例。
另外,如果我的 function 正在重新發明輪子,請告訴我。 我正在使用 .NET 3.5
提前致謝。
嘗試:
str = str.Replace(c.ToString(), String.Empty);
請注意, string
的實例是不可變的。 因此,您需要分配String.Replace
的結果,否則結果會丟失。
沒有空字符,所以使用字符串重載:
str = str.Replace( c.ToString(), "");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.