![](/img/trans.png)
[英]How can i replace many special character including white space with single character?
[英]How can I replace no digit character with space character?
我想用空格字符替换字符串中的每个非数字 字符 。
例如: "123X456Y78W9" -> "123 456 78 9"
我得出的唯一解决方案是:
string input = "123X456Y78W9";
string output = "";
foreach (char c in input)
if (c in (1, 2, 3, 4, 5, 6, 7, 8, 9, 0))
output += c;
else
output += ' ';
有没有更简单的解决方案?
您可以将Regex.Replace()
与所有非数字字符类一起使用。
string output = Regex.Replace(input, @"\D", @" ");
Linq是正则表达式的替代方法:
string input = "123X456Y78W9";
string output = string.Concat(input.Select(c => c >= '0' && c <= '9' ? c : ' '));
或者,如果您想保留所有unicode数字 (例如, 波斯 数字 ۰ ۱ ۲ ۳ ۴ ۵ ۶ ۷ ۸ ۹
)
string output = string.Concat(input.Select(c => char.IsDigit(c) ? c : ' '));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.