如何从一个字符串中删除字符,除了那些在列表(How to remove characters fro

2019-08-03 21:26发布

这是我的字符串值:

string str = "32 ab d32";

而这个名单是我的允许的字符:

var allowedCharacters = new List<string> { "a", "b", "c", "2", " " };

我希望它变成:

str == " 2 ab   2";

我想更换,是不是在允许的角色列表中的任何字符,一个空的空间。

Answer 1:

正则表达式? 正则表达式可能是矫枉过正为您所要完成的任务。

这里是没有正则表达式另一种变体(修改您的lstAllowedCharacters实际上是一个枚举的字符 ,而不是字符串[作为变量名称所暗示的):

String original = "32 ab d32";
Char replacementChar = ' ';
IEnumerable<Char> allowedChars = new[]{ 'a', 'b', 'c', '2', ' ' };

String result = new String(
  original.Select(x => !allowedChars.Contains(x) ? replacementChar : x).ToArray()
);


Answer 2:

没有正则表达式:

IEnumerable<Char> allowed = srVariable
    .Select(c => lstAllowedCharacters.Contains(c.ToString()) ? c : ' ');
string result = new string(allowed.ToArray());


Answer 3:

试试这个:

string srVariable = "32 ab d32";
List<string> lstAllowedCharacters = new List<string> { "a", "b", "c", "2", " " };

srVariable = Regex.Replace(srVariable, "[^" + Regex.Escape(string.Join("", lstAllowedCharacters) + "]"), delegate(Match m)
{
    if (!m.Success) { return m.Value; }
    return " ";
});

Console.WriteLine(srVariable);


Answer 4:

下面是一个简单而高性能的foreach的解决方案:

Hashset<char> lstAllowedCharacters = new Hashset<char>{'a','b','c','2',' '};

var resultStrBuilder = new StringBuilder(srVariable.Length);

foreach (char c in srVariable) 
{
    if (lstAllowedCharacters.Contains(c))
    {
        resultStrBuilder.Append(c);
    }
    else
    {
        resultStrBuilder.Append(" ");
    }
}

srVariable = resultStrBuilder.ToString();


Answer 5:

你为什么不使用与string.replace ?



文章来源: How to remove characters from a string, except those in a list