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

僤鯓⒐⒋嵵緔 提交于 2019-12-20 03:52:20

问题


This is my string value:

string str = "32 ab d32";

And this list is my allowed characters:

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

I want it to become:

str == " 2 ab   2";

I would like to replace any character that is not in the allowed character list, with an empty space.


回答1:


Regex? Regex may be overkill for what you're trying to accomplish.

Here's another variation without regex (modified your lstAllowedCharacters to actually be an enumerable of characters and not strings [as the variable name implies]):

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()
);



回答2:


Without regex:

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



回答3:


Try this:

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);



回答4:


Here is a simple but performant foreach solution:

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();



回答5:


Why don't you use String.Replace?



来源:https://stackoverflow.com/questions/13824649/how-to-remove-characters-from-a-string-except-those-in-a-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!