C#:去除字符串中的多个无效字符

C#: get rid of multiple invalid characters in string

我是 C# 新手。假设我有这样一个字符串:

string test = 'yes/, I~ know# there@ are% invalid£ characters$ in& this* string^";

如果我想删除单个无效符号,我会这样做:

if (test.Contains('/')) 
{ 
    test = test.Replace("/","");
} 

但是有没有一种方法可以使用符号列表作为 ContainsReplace 函数的参数,而不是一个一个地删除符号?

我认为没有开箱即用的功能。

我认为您的想法非常正确,尽管在我看来您并不真正需要 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, @"\/|~|#|@|%|£|$|&|\*|\^", "");

为每个字符添加一个|或参数并使用replace

请记住 \/ 表示 / 但您需要转义该字符。

您的解决方案是:

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 可以做到这一点。