簡體   English   中英

在 C# 中將字符串格式化為電話號碼

[英]Format String as phone number in C#

我在 C# 中有一個字符串值 1233873600,我必須在 C# 中將其轉換為 123-387-7300

是否有任何內置函數可以在 c# 中做到這一點?

將您的字符串轉換為長字符串並使用格式"{0:### ### ####}" ;

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

您可以使用一個簡單的輔助方法來獲取字符串,對輸入進行消毒以刪除用作分隔符的空格或不需要的特殊字符,然后使用內置的 ToString 方法。 如果您檢查各種長度,您還可以確保格式符合您的要求。 例如:

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;
    }

我認為正則表達式是最好的選擇。

該站點非常適合查找預先制作的正則表達式字符串。

http://www.regexlib.com/

您可能想為此使用正則表達式。 北美電話號碼的正則表達式如下所示

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

我猜你可以在 C# 中使用Regex.Replace方法。

字符串格式對我不起作用,所以我做了:

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