How to remove characters from a string, except those in a list

后端 未结 5 1977
感情败类
感情败类 2021-01-24 05:16

This is my string value:

string str = \"32 ab d32\";

And this list is my allowed characters:

var allowedCharacters = new List&l         


        
5条回答
  •  执笔经年
    2021-01-24 05:55

    Here is a simple but performant foreach solution:

    Hashset lstAllowedCharacters = new Hashset{'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();
    

提交回复
热议问题