简体   繁体   English

如何用空格字符代替数字字符?

[英]How can I replace no digit character with space character?

I'd like to replace every not digit character in string with a space character . 我想用空格字符替换字符串中的每个非数字 字符

For ex.: "123X456Y78W9" -> "123 456 78 9" 例如: "123X456Y78W9" -> "123 456 78 9"

Only resolution that I worked out is here: 我得出的唯一解决方案是:

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 += ' ';

Is there are any simpler resolution? 有没有更简单的解决方案?

您可以将Regex.Replace()与所有非数字字符类一起使用。

string output = Regex.Replace(input, @"\D", @" ");

Linq is an alternative to regular expressions : Linq正则表达式的替代方法:

string input = "123X456Y78W9"; 

string output = string.Concat(input.Select(c => c >= '0' && c <= '9' ? c : ' '));

Or if you want to preserve all unicode digits (say, persian ones - ۰ ۱ ۲ ۳ ۴ ۵ ۶ ۷ ۸ ۹ ) 或者,如果您想保留所有unicode数字 (例如, 波斯 数字 ۰ ۱ ۲ ۳ ۴ ۵ ۶ ۷ ۸ ۹

string output = string.Concat(input.Select(c => char.IsDigit(c) ? c : ' '));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM