简体   繁体   中英

Format String as phone number in C#

I have 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#?

将您的字符串转换为长字符串并使用格式"{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, "-");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM