6

The string displays value as:

123456789012

I need it like:

1234 5678 9012

There should be space between every 4 characters in this string. How do I do that?

displaynum_lbl.Text = Regex.Replace(printClass.mynumber.ToString(), ".{4}", "$0");
alex dave
  • 115
  • 1
  • 4
  • 10

4 Answers4

12

Assuming that it's fine to work from right-to-left, this should do the trick:

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

You can find that and a good deal more information in other StackOverflow answers, example: Add separator to string at every N characters?

Community
  • 1
  • 1
Jonathan
  • 6,507
  • 5
  • 37
  • 47
12
        String abc = "123456789012";

        for (int i = 4; i <= abc.Length; i += 4)
        {
            abc = abc.Insert(i, " ");
            i++;
        }
DhavalR
  • 1,409
  • 3
  • 29
  • 57
3

You can do this in 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

Icemanind
  • 47,519
  • 50
  • 171
  • 296
1
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);
}
Bryce Wagner
  • 2,640
  • 1
  • 26
  • 43