如何在一个字符串中插入一个空格,每4个字符之间?

时间:2015-01-16 03:53:29

标签: c# string

字符串显示值为:

123456789012

我需要它:

1234 5678 9012

此字符串中每4个字符之间应该有空格。我该怎么做?

displaynum_lbl.Text = Regex.Replace(printClass.mynumber.ToString(), ".{4}", "$0");

4 个答案:

答案 0 :(得分:7)

        String abc = "123456789012";

        for (int i = 4; i <= abc.Length; i += 4)
        {
            abc = abc.Insert(i, " ");
            i++;
        }

答案 1 :(得分:2)

您可以在LINQ中执行此操作:

var s = "123456789012";
var list = Enumerable
    .Range(0, s.Length/4)
    .Select(i => s.Substring(i*4, 4))
    .ToList();
var res = string.Join(" ", list);
Console.WriteLine(res);

Fiddle

答案 2 :(得分:1)

假设从右到左工作很好,这应该可以解决问题:

displaynum_lbl.Text = System.Text.RegularExpressions.Regex.Replace(printClass.mynumber.ToString(), ".{4}", "$0 ");

您可以在其他StackOverflow答案中找到更多信息,例如:Add separator to string at every N characters?

答案 3 :(得分:0)

public string InsertSpaces(string s)
{
    char[] result = new char[s.Length + (s.Length / 4)];

    for (int i = 0, target = 0; i < s.Length; i++)
    {
        result[target++] = s[i];
        if (i & 3 == 3)
            result[target++] = ' ';
    }
    return new string(result);
}