Fastest way to format a phone number in C#?

后端 未结 5 1624
生来不讨喜
生来不讨喜 2020-12-10 01:25

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.

5条回答
  •  感动是毒
    2020-12-10 01:50

    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.

提交回复
热议问题