Format String as phone number in C#
I ha开发者_StackOverflowve a string value 1233873600 in C# and I have to convert it to 123-387-7300 in C#
Is there any in-built function which will do that in c#?
Cast your string to a long and use the format "{0:### ### ####}"
;
string.Format("{0:(###) ###-####}", 1112223333);
string phone = "1233873600".Insert(6, "-").Insert(3, "-");
You can use a simple helper method that will take the string, sterilize the input in order to remove spaces or unwanted special characters being used as a separator, and then use the ToString method built-in. If you check for various lengths you can also assure the format comes out as you see fit. For example:
public string FormatPhoneNumber(string phoneNumber)
{
string originalValue = phoneNumber;
phoneNumber= new System.Text.RegularExpressions.Regex(@"\D")
.Replace(phoneNumber, string.Empty);
value = value.TrimStart('1');
if (phoneNumber.Length == 7)
return Convert.ToInt64(value).ToString("###-####");
if (phoneNumber.Length == 9)
return Convert.ToInt64(originalValue).ToString("###-###-####");
if (phoneNumber.Length == 10)
return Convert.ToInt64(value).ToString("###-###-####");
if (phoneNumber.Length > 10)
return Convert.ToInt64(phoneNumber)
.ToString("###-###-#### " + new String('#', (phoneNumber.Length - 10)));
return phoneNumber;
}
I think regex is the best option.
this site is great for finding pre made regex strings.
http://www.regexlib.com/
You might want to use regex for this. The regex for North America phone number looks like this
^(\(?[0-9]{3}\)?)?\-?[0-9]{3}\-?[0-9]{4}$
I guess you can use Regex.Replace
method in C#.
String Format didn't work for me, so I did:
string nums = String.Join("", numbers);
return nums.Insert(0, "(").Insert(4, ")").Insert(5, " ").Insert(9, "-");
精彩评论