简体   繁体   中英

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

My source format is a string.

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

Will result in (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" :

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. 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.

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".

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

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