简体   繁体   English

在 C# 中将字符串格式化为电话号码

[英]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#我在 C# 中有一个字符串值 1233873600,我必须在 C# 中将其转换为 123-387-7300

Is there any in-built function which will do that in c#?是否有任何内置函数可以在 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.您可以使用一个简单的辅助方法来获取字符串,对输入进行消毒以删除用作分隔符的空格或不需要的特殊字符,然后使用内置的 ToString 方法。 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/ 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#.我猜你可以在 C# 中使用Regex.Replace方法。

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, "-");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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