Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert a space into a string, between every 4 characters? [duplicate]

Tags:

string

c#

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");
like image 715
alex dave Avatar asked Nov 29 '22 14:11

alex dave


2 Answers

        String abc = "123456789012";

        for (int i = 4; i <= abc.Length; i += 4)
        {
            abc = abc.Insert(i, " ");
            i++;
        }
like image 145
DhavalR Avatar answered Dec 18 '22 10:12

DhavalR


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?

like image 34
Jonathan Avatar answered Dec 18 '22 08:12

Jonathan