Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert spaces into string using string.format

Tags:

c#

I've been using C# String.Format for formatting numbers before like this (in this example I simply want to insert a space):

String.Format("{0:### ###}", 123456);

output:

"123 456"

In this particular case, the number is a string. My first thought was to simply parse it to a number, but it makes no sense in the context, and there must be a prettier way.

Following does not work, as ## looks for numbers

String.Format("{0:### ###}", "123456");

output:

"123456"

What is the string equivalent to # when formatting? The awesomeness of String.Format is still fairly new to me.

like image 436
Scherling Avatar asked Oct 07 '14 10:10

Scherling


2 Answers

You have to parse the string to a number first.

int number = int.Parse("123456");
String.Format("{0:### ###}", number);

of course you could also use string methods but that's not as reliable and less safe:

string strNumber =  "123456";
String.Format("{0} {1}", strNumber.Remove(3), strNumber.Substring(3));
like image 118
Tim Schmelter Avatar answered Sep 21 '22 15:09

Tim Schmelter


As Heinzi pointed out, you can not have format specifier for string arguments.

So, instead of String.Format, you may use following:

string myNum="123456";
myNum=myNum.Insert(3," ");
like image 22
Shubhada Fuge Avatar answered Sep 20 '22 15:09

Shubhada Fuge