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

0 c# string algorithm

我想用空格字符替换字符串中的每个非数字字符

例如: "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 += ' ';
Run Code Online (Sandbox Code Playgroud)

有没有更简单的解决方案?

sti*_*bit 7

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

string output = Regex.Replace(input, @"\D", @" ");
Run Code Online (Sandbox Code Playgroud)

  • 旁注:“ @” \ D”不表示任何* unicode位数*(不仅是“ 0..9”,而且还包括许多其他字符,例如波斯语-“ code”)。如果只保留“ 0..9”,则将“ RegexOptions.ECMAScript”添加为最后一个参数:“ Regex.Replace(input,@“ \ D”,“”,RegexOptions.ECMAScript);` (2认同)