Home > Back-end >  C# Formatting a string with string.Format("00-00-00")
C# Formatting a string with string.Format("00-00-00")

Time:07-17

I am attempting convert this string "123456" to "12-34-56". I try to use this code but it doesn't seem to work correctly

string.Format("00-00-00", "123456");

Can anyone help me find a suitable pattern? Thanks for any help

CodePudding user response:

Use below

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

If number is represented as string the convert to int

string.Format("{0:##-##-##}", Convert.ToInt32("123456"));

The above will print the output as

12-34-56

CodePudding user response:

Your format string is not correct, composite formatted string should be enclosed within curly braces and can have three parameters as follows,

{ index[,alignment][:formatString] }

While alignment and formatString are optional, index is mandatory.

In your case, it is a single string "123456" with index 0 which is to be formatted in the following pattern "12-34-56".

So, we use the index and format string to achieve the desired output.

To represent a digit 0-9 (optional) in the format string, we use the placeholder '#'.

'#' holds 0, if there exists no digit corresponding to the position in the object, else it replaces the 0 with the digit in place.

The following format string would be suitable for your need,

##-##-## -> three numbers with 2 digits each separated by a hyphen.

Now, putting that in place using the composite format syntax, "{0:##-##-##}"

Usage:

String input:

var s = "123456";
Console.WriteLine("{0:##-##-##}", Convert.ToInt32(s));

Integer input:

var n = 123456;
Console.WriteLine("{0:##-##-##}", n);
  •  Tags:  
  • c#
  • Related