从右到左每N个元素分隔一个字符串

时间:2016-01-22 10:24:42

标签: c# regex

我有以下字符串“ 23456789
我需要它成为“ 23 456 789 ”。

我发现了这个:

Regex.Replace(MYString, ".{3}", "$0 ");

但数字变为“ 234 567 89 ”。

它不一定是正则表达式,一切都受到欢迎。 谢谢

7 个答案:

答案 0 :(得分:3)

您可以将其解析为decimal并使用空格为group-separator的自定义NumberFormatInfo

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())));

答案 1 :(得分:0)

Tim answer适用于十进制值,但对于非常大的数字,有更多通用解决方案。请注意,它是性能杀手,因为我们几次声明新数组和复制数据:

string myString = "95555554643674373734737443737";
// revert source string
string reversedList = new string(myString.Reverse().ToArray());
// replace each trio
string replacedReversedList = Regex.Replace(reversedList, ".{3}", "$0 ");
// revert replaced string back to normal direction
string result = new string(replacedReversedList.Reverse().ToArray());

string oneLineResult = new string(Regex.Replace(new string(myString.Reverse().ToArray()), ".{3}", "$0 ").Reverse().ToArray());

答案 2 :(得分:0)

不需要解析/格式化任何东西或多个循环(如Reverse,ToArray等):

private static String CreateGroups(string source, int groupSize)
{
    if (groupSize <= 0)
        throw new ArgumentOutOfRangeException("groupSize", "must be greater zero.");

    var sb = new StringBuilder();
    var firstGroupLength = source.Length % groupSize;
    var groupLength = firstGroupLength == 0 ? groupSize : firstGroupLength;

    foreach (var item in source)
    {
        sb.Append(item);
        groupLength--;

        if (groupLength == 0)
        {
            groupLength = groupSize;
            sb.Append(' ');
        }
    }

    return sb.ToString(0, sb.Length-1);
}

答案 3 :(得分:0)

使用此代码添加命名空间using System.Globalization;

var nfi = (NumberFormatInfo)CultureInfo.InvariantCulture.NumberFormat.Clone();
            nfi.NumberGroupSeparator = " ";

            string formatted = 23456789m.ToString("#,#", nfi);

答案 4 :(得分:0)

我只针对一般情况这样做:

string test = "23456789";
int n = 3; // Or whatever grouping you want.

for (int i = test.Length - n; i > 0; i -= n)
    test = test.Insert(i, " ");

Console.WriteLine(test);

但是如果你真的想要格式化一个数字而不是一个字符串,我会在这个帖子中使用其他一个基于数字的答案。

答案 5 :(得分:0)

这有效:

var MyString = "23456789";

var result =
    new string(
        MyString
            .Reverse()
            .SelectMany((x, n) =>
                new [] { x }.Concat(n % 3 == 2
                    ? new [] { ' ' } 
                    : Enumerable.Empty<char>()))
            .Reverse()
            .ToArray());

我得到了所需的"23 456 789"

答案 6 :(得分:0)

这是我的看法。

这不需要强制转换为数字类型,您可以改变块的大小

public static string Separate(this string source, int chunkSize = 3)
{
  return string.Concat(source.Select((x, i) => (source.Length - i - 1) % chunkSize == 0 ? x + " " : x.ToString()));
}

用法:

string str = "23456789";
var separatedBy3 = str.Separate(); //23 456 789

var separatedy4 = str.Separate(4); //2345 6789
相关问题