Format String as a phone number in C #

I have a string value of 1233873600 in C # and I have to convert it to 123-387-7300 in C #

Is there a built-in function that will do this in C #?

+5
source share
5 answers

You might want to use regex for this. The regular expression number for North America is as follows:

^(\(?[0-9]{3}\)?)?\-?[0-9]{3}\-?[0-9]{4}$

I think you can use the method Regex.Replacein C #.

0
source

Copy the string to a long one and use the format "{0:### ### ####}";

string.Format("{0:(###) ###-####}", 1112223333);
+8
source
string phone = "1233873600".Insert(6, "-").Insert(3, "-");
+3
+1

You can use a simple helper method that will take a string, sterilize the input to remove spaces or unwanted special characters used as a delimiter, and then use the built-in ToString method. If you check different lengths, you can also make sure that the format comes out as you see fit. For instance:

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;
    }
+1
source

All Articles