Format String as phone number 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;
    }

Tags:

C#