我有以下字符串“23456789”
我需要它变成“23 456 789”。
我发现了这个:
Regex.Replace(MYString, ".{3}", "$0 ");
但数字变为“234 567 89”。
不必是Regex,什么都欢迎。谢谢
您可以将其解析为 decimal
并使用带有空格的自定义 NumberFormatInfo
group-separator :
string input = "23456789";
decimal d = decimal.Parse(input);
var nfi = (NumberFormatInfo)CultureInfo.InvariantCulture.NumberFormat.Clone();
nfi.NumberGroupSeparator = " ";
nfi.NumberDecimalDigits = 0;
string formatted= d.ToString("N", nfi);
参见:The Numeric ("N") Format Specifier
物有所值。这是一种不仅适用于数字字符串而且适用于所有类型的字符串甚至任何类型的对象的方法(如果您删除 string.Join
):
string result = String.Join(" ", input.Reverse() // reverse input to get proper groups from right to left
.Select((c, index) => new { Char = c, Index = index })
.GroupBy(x => x.Index / 3, x=> x.Char) // group by index using integer division and then output the char
.Reverse() // again reverse to get original order
.Select(charGroup => new String(charGroup.Reverse().ToArray())));
我是一名优秀的程序员,十分优秀!