简体   繁体   English

在 C# 中格式化电话号码的最快方法?

[英]Fastest way to format a phone number in C#?

What is the fastest way to format a string using the US phone format [(XXX) XXX-XXXX] using c#?使用 c# 使用美国电话格式 [(XXX) XXX-XXXX] 格式化字符串的最快方法是什么?

My source format is a string.我的源格式是一个字符串。

String.Format("{0:(###) ###-#### x ###}", double.Parse("1234567890123"))

Will result in (123) 456-7890 x 123将导致 (123) 456-7890 x 123

This assumes that you have the phone number with the appropriate number of digits stored like:这假设您拥有存储有适当位数的电话号码,例如:

string p = "8005551234";

string formatedPhoneNumber = string.Format("({0}) {1}-{2}", p.Substring(0, 3), p.Substring(3, 3), p.Substring(6, 4));

This will take a string containing ten digits formatted in any way, for example "246 1377801" or even ">> Phone:((246)) 13 - 778 - 01 <<" , and format it as "(246) 137-7801" :这将接受一个包含十位数字的字符串,以任何方式格式化,例如"246 1377801"甚至">> Phone:((246)) 13 - 778 - 01 <<" ,并将其格式化为"(246) 137-7801" :

string formatted = Regex.Replace(
   phoneNumber,
   @"^\D*(\d)\D*(\d)\D*(\d)\D*(\d)\D*(\d)\D*(\d)\D*(\d)\D*(\d)\D*(\d)\D*(\d)\D*$",
   "($1$2$3) $4$5$6-$7$8$9$10");

(If the string doesn't contain exactly ten digits, you get the original string unchanged.) (如果字符串不完全包含十位数字,则原始字符串将保持不变。)

Edit:编辑:

A fast ways to build a string is to use a StringBuilder.构建字符串的一种快速方法是使用 StringBuilder。 By setting the capacity to the exact length of the final string you will be working with the same string buffer without any reallocations, and the ToString method will return the buffer itself as the final string.通过将容量设置为最终字符串的确切长度,您将使用相同的字符串缓冲区而不进行任何重新分配,并且 ToString 方法将缓冲区本身作为最终字符串返回。

This assumes that the source string contains only the ten digits:这假定源字符串仅包含十位数字:

string formatted =
   new StringBuilder(14)
   .Append('(')
   .Append(phoneNumber, 0, 3)
   .Append(") ")
   .Append(phoneNumber, 3, 3)
   .Append('-')
   .Append(phoneNumber, 6, 4)
   .ToString();

I would assume it'd be:我会假设它是:

var number = string.Format("({0}) {1}-{2}", oldNumber.Substring(0, 3), oldNumber.Substring(3, 3), oldNumber.Substring(6));

This assumes that you have the number stored as "1234567890" and want it to be "(123) 456-7890".这假设您将号码存储为“1234567890”并希望它是“(123) 456-7890”。

Not the fastest way, but you can use Extension Methods (note that the parameter must be cleaned up of any previous phone format):不是最快的方法,但您可以使用扩展方法(注意该参数必须清除任何以前的电话格式):

public static class StringFormatToWhatever
{
    public static string ToPhoneFormat(this string text)
    {        
        string rt = "";
        if (text.Length > 0)
        {            
            rt += '(';
            int n = 1;
            foreach (char c in text)
            {
                rt += c;
                if (n == 3) { rt += ") "; }
                else if (n == 6) { rt += "-"; }
                n++;
            }
        }
        return rt;
    }
}

Then, use it as然后,将其用作

myString.ToPhoneFormat();

Modify to your needs if you want to:如果您愿意,请根据您的需要进行修改:

  • Include phone extension (x1234)包括电话分机 (x1234)
  • Clean the parameter of any existing phone format inside the method清除方法内任何现有电话格式的参数
  • Use dash instead of parenthesis使用破折号代替括号
  • Eat a sandwich... you name it: :)吃一个三明治......你的名字::)

You can also use this to format the string in each user input.您还可以使用它来格式化每个用户输入中的字符串。

    private void txtPhone_Update()       
        {
            string phone = "";
            string phone1 = "";
            int index = 0;
            phone = txtPhone.Text;
            phone1 = "";

            for (index = 0; index < phone.Length; index++)
                if (char.IsDigit(phone[index]))
                { phone1 += phone[index]; }

                {
                    if (phone1[0] == '1') { phone1 = phone1.Remove(0, 1); }

                    {
                            string number = "";
                            number = string.Format("({0}) {1}-{2}", phone1.Substring(0, 3), phone1.Substring(3, 3), phone1[6..]);
                            phone1 = number;
                    }
                }
    }

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

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