gpt4 book ai didi

c# - 从右到左每 N 个元素分隔字符串

转载 作者:太空宇宙 更新时间:2023-11-03 23:22:28 24 4
gpt4 key购买 nike

我有以下字符串“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())));

关于c# - 从右到左每 N 个元素分隔字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34944351/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com