如何从字符串中删除字符,除了列表中的字符 [英] How to remove characters from a string, except those in a list
本文介绍了如何从字符串中删除字符,除了列表中的字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我的字符串值:
string str = "32 ab d32";
此列表是我允许的字符:
And this list is my allowed characters:
var allowedCharacters = new List<string> { "a", "b", "c", "2", " " };
我希望它变成:
str == " 2 ab 2";
我想用空格替换任何不在允许字符列表中的字符。
I would like to replace any character that is not in the allowed character list, with an empty space.
推荐答案
Regex?
这里是另一个没有regex的变体(修改你的 lstAllowedCharacters
实际上是可枚举的字符而不是字符串[作为变量名称的含义]):
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()
);
这篇关于如何从字符串中删除字符,除了列表中的字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文