show string in a desire format

78 Views Asked by At

I want to show my string in a special format.
For example I have a string like this s = "00012345"; and want to show it in this format 000(123-45)

I use this code for it:

label1.text = string.format("{0,###(###-##)}",s);

But just see this for result: 00012345.

What string formatting should I be using?

2

There are 2 best solutions below

2
On BEST ANSWER

As mentioned you can't format an already existing string. First you need to convert the string to an int:

int num = Int32.TryParse(s);

Then you can do the formatting whilst converting it back into a string:

label1.text = num.ToString("000(000-00)");
1
On
string s = "00012345";
string s1 = s.Substring(0,3);
string s2 = s.Substring(3,3);
string s3 = s.Substring(6);
s = string.Format("{0}({1}-{2})", s1,s2,s3);