6

I have a string value 1233873600 in C# and I have to convert it to 123-387-7300 in C#

Is there any in-built function which will do that in c#?

acadia
  • 2,619
  • 18
  • 55
  • 72
  • no there isn't, but you can easily write your own. – Mitch Wheat Jan 20 '11 at 14:32
  • possible duplicate of [How to format a string as a telephone number in C#](http://stackoverflow.com/questions/188510/how-to-format-a-string-as-a-telephone-number-in-c) – stuartd Jan 20 '11 at 14:34

6 Answers6

12

Cast your string to a long and use the format "{0:### ### ####}";

string.Format("{0:(###) ###-####}", 1112223333);
Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
hunter
  • 62,308
  • 19
  • 113
  • 113
3
string phone = "1233873600".Insert(6, "-").Insert(3, "-");
Greg
  • 16,540
  • 9
  • 51
  • 97
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. 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;
    }
Victor Johnson
  • 111
  • 1
  • 4
1

I think regex is the best option.

this site is great for finding pre made regex strings.

http://www.regexlib.com/

WraithNath
  • 17,658
  • 10
  • 55
  • 82
0

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

Max Al Farakh
  • 4,386
  • 4
  • 29
  • 56
  • using a format string would be the preferred method of doing this. both more readable and computationally faster. – cazlab Oct 24 '13 at 14:27
0

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, "-");
Dragana
  • 101
  • 1
  • 3
  • 8