2011-06-06 29 views
1

我有以下擴展方法(這是無效的,並且不編譯ATM):C#:如何使用字符重載爲string.Replace()來取代沒有?

public static string Strip(this string str, char[] charsToStrip) 
    { 
     foreach(char c in charsToStrip) 
     { 
      str.Replace(c, ""); 
     } 

     return str; 
    } 

的str.Replace()調用需要調用替換()的「字符」過載,但使用這種過載我不確定要傳入第二個參數以告訴它用「無」替換。

此函數的目標是迭代charsToStrip變量中的每個字符,並刪除源字符串str中該字符的所有實例。

此外,如果我的功能是重新發明輪子,讓我知道。我正在使用.NET 3.5

在此先感謝。

回答

8

嘗試:

str = str.Replace(c.ToString(), String.Empty); 

注意的string實例是不可變的。因此,您需要指定String.Replace的結果,否則結果將丟失。

2

沒有空字符,所以使用一個字符串超載:

str = str.Replace(c.ToString(), ""); 
+0

'Replace'不是''上string' static'方法。 – jason 2011-06-06 13:33:23

+0

更正,謝謝。 – Zruty 2011-06-06 13:34:34

+0

我假設它只是僞代碼。 – 2011-06-06 13:34:38

相關問題