我是C#的新手。假设我有这样的字符串:
string test = 'yes/, I~ know# there@ are% invalid£ characters$ in& this* string^";
如果我想摆脱一个无效的符号,我会这样做:
if (test.Contains('/'))
{
test = test.Replace("/","");
}
但是有一种方法可以使用符号列表作为Contains
和Replace
函数的参数,而不是一个一个地删除符号?
定义可接受的字符可能比尝试思考和编码需要消除的所有内容要好。
因为您提到自己正在学习,所以听起来像是学习正则表达式的最佳时机。这里有几个链接可以帮助您入门:
我认为没有现成的功能。
我认为您的想法几乎是正确的,尽管我认为您实际上并不需要if(test.Contains(..))
部分。这样做,一旦您迭代了字符串的字符以查看该元素是否存在(如果确实在字符串中,则在最后),请替换它]
立即替换特殊字符会更快。所以...
List<string> specialChars = new List<string>() {"*", "/", "&"}
for (var i = 0; i < specialChars.Count; i++)
{
test = test.Replace(specialChars[i],"");
}
我会使用正则表达式解决方案
string test = Regex.Replace(test, @"@|\/|%", "");
为每个字符添加|
或参数并使用替换
请记住\/
的意思是/
,但您需要转义字符。
您的解决方案是:
Path.GetInvalidPathChars()
所以代码看起来像这样:
string illegal = "yes/, I~ know# there@ are% invalid£ characters$ in& this* string^";
string invalid = new string(Path.GetInvalidFileNameChars()) + new
string(Path.GetInvalidPathChars());
foreach (char c in invalid)
{
illegal = illegal.Replace(c.ToString(), "");
}
另一种变体:
List<string> chars = new List<string> {"!", "@"};
string test = "My funny! string@";
foreach (var c in chars)
{
test = test.Replace(c,"");
}
不需要像Contains
那样使用Replace
。