[英]C#: How to use the char overload for string.Replace() to replace with nothing?
I have the following extension method (which is invalid and does not compile ATM):我有以下扩展方法(无效且不编译 ATM):
public static string Strip( this string str, char[] charsToStrip )
{
foreach( char c in charsToStrip )
{
str.Replace( c, "" );
}
return str;
}
The str.Replace() call needs to invoke the 'char' overload of Replace(), however using this overload I'm not sure what to pass into the 2nd parameter to tell it to replace with "nothing". str.Replace() 调用需要调用 Replace() 的 'char' 重载,但是使用此重载我不确定将什么传递给第二个参数以告诉它用“nothing”替换。
The goal of this function is to iterate each character in the charsToStrip
variable and remove all instances of that character in the source string, str
.此 function 的目标是迭代
charsToStrip
变量中的每个字符并删除源字符串str
中该字符的所有实例。
Also if my function is reinventing the wheel, let me know.另外,如果我的 function 正在重新发明轮子,请告诉我。 I'm using .NET 3.5
我正在使用 .NET 3.5
Thanks in advance.提前致谢。
Try:尝试:
str = str.Replace(c.ToString(), String.Empty);
Note that instances of string
are immutable.请注意,
string
的实例是不可变的。 As such, you need to assign the result of String.Replace
otherwise the result is lost.因此,您需要分配
String.Replace
的结果,否则结果会丢失。
There is no empty char, so use a string overload:没有空字符,所以使用字符串重载:
str = str.Replace( c.ToString(), "");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.