tim.baker
tim.baker

Reputation: 3307

MVC/C# Put a comma after every number in string

I have a string of 4 numbers:

1234

I want to convert this in the most elegant way possible in MVC to

1,2,3,4

I've tried this:

codeToSend.ToString("#,#");

but this outputs "1,234" (which I expected really).

I suspected that the following would put a comma after every digit, but to no avail.

codeToSend.ToString("#,#,#,#");

I have also tried string.format, but again I am facing the same issue.

var formattedString = string.Format("{0:0,0}", 1234);

Whats the most efficient way of doing this therefore?

Note: The string of numbers will always be 4 digits long - and numbers only. I don't want to use Insert as this wouldn't be very elegant IMO and I am aware this question has been asked before in similar ways but it is always slightly different in crucial ways (such as formatting to thousands, not every digit or just not elegantly!).

Upvotes: 0

Views: 1110

Answers (2)

Uladz
Uladz

Reputation: 1968

This one could be more efficient. (But hardly elegant)

var target = "1234";
var result = Regex.Replace(target , @"(\d)(?=.)", "$1,");

Taking fixed string length into account, the same result could be acomplished without lookahead (simpler for reading, and with better efficiency)

var target = "1234";
var result = Regex.Replace(target, @"(\d)(\d)(\d)(\d)", "$1,$2,$3,$4");

Also, if you are processing many such values, you should compile regex before using.

 var target = "1234";
 var digitExceptLastRegex = new Regex(@"(\d)(?=.)", RegexOptions.Compiled);
 var result = regex.Replace(target, "$1,");

But I haven't measured actual performance.

Upvotes: 0

Soner Gönül
Soner Gönül

Reputation: 98750

How about just using string.Join?

int i = 1234;
string.Join(",", i.ToString().ToCharArray()); // 1,2,3,4

If 1234 is string, just use;

string s = "1234";
string.Join(",", s.ToCharArray()); // 1,2,3,4

or

string s = "1234";
string.Join(",", s.ToList()); // 1,2,3,4

Upvotes: 5

Related Questions