简体   繁体   中英

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"

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 :

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 - ۰ ۱ ۲ ۳ ۴ ۵ ۶ ۷ ۸ ۹ )

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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