且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何从字符串中删除字符,除了列表中的字符

更新时间:2023-12-04 20:44:46

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