views:

8227

answers:

11

I have a string "1112224444' it is a telephone number. I want to format as 111-222-4444 before I store it in a file. It is on a datarecord and I would prefer to be able to do this without assigning a new variable.

I was thinking:

String.Format("{0:###-###-####}", i["MyPhone"].ToString() );

but that does not seem to do the trick.

** UPDATE **

Ok. I went with this solution

Convert.ToInt64(i["Customer Phone"]).ToString("###-###-#### ####")

Now its gets messed up when the extension is less than 4 digits. It will fill in the numbers from the right. so

1112224444 333  becomes

11-221-244 3334

Any ideas?

+1  A: 

As far as I know you can't do this with string.Format ... you would have to handle this yourself. You could just strip out all non-numeric characters and then do something like:

string.Format("({0}) {1}-{2}",
     phoneNumber.Substring(0, 3),
     phoneNumber.Substring(3, 3),
     phoneNumber.Substring(6));

This assumes the data has been entered correctly, which you could use regular expressions to validate.

mattruma
And it assumes a north american phone number
chris
And last substring should be corrected to .Substring(6)
Shrage Smilowitz
Fixed ... thanks @Shrage Smilowitz!
mattruma
+3  A: 

You'll need to break it into substrings. While you could do that without any extra variables, it wouldn't be particularly nice. Here's one potential solution:

string phone = i["MyPhone"].ToString();
string area = phone.Substring(0, 3);
string major = phone.Substring(3, 3);
string minor = phone.Substring(6);
string formatted = string.Format("{0}-{1}-{2}", area, major, minor);
Jon Skeet
Jon are you sure making three substrings is better than using string.format?
Pradeep
I use String.Format as well - but how are you suggesting to achieve the result *without* using String.Format?
Jon Skeet
+2  A: 

If you can get i["MyPhone"] as a long, you can use the long.ToString() method to format it:

Convert.ToLong(i["MyPhone"]).ToString("###-###-####");

See the MSDN page on Numeric Format Strings.

Be careful to use long rather than int: int could overflow.

Joel Coehoorn
+7  A: 

I prefer to use regular expressions:

Regex.Replace("1112224444", @"(\d{3})(\d{3})(\d{4})", "$1-$2-$3");
Ryan Duffield
I suppose this would work, but the .ToString() format is easier to read and should perform better.
Joel Coehoorn
If I'm dealing with a string already, as the poster has said, casting it to a long and back again seems silly.
Ryan Duffield
Maybe this is what I need after all. may handle the extension better
Brian G
+1 for not treating a telephone number as a numeric value.
statenjason
+1 for keeping the number as a string (given that often phone numbers used for automated SMS systems have to be stored in the +44 format)
Ed Woodcock
+17  A: 

From a good page full of examples:

String.Format(”{0:(###) ###-####}”, 8005551212);

    This will output “(800) 555-1212″.

Although a regex may work even better, keep in mind the old programming quote:

Some people, when confronted with a problem, think “I know, I’ll use regular expressions.” Now they have two problems.
--Jamie Zawinski, in comp.lang.emacs

Sean
I love that quote.
AMissico
+1  A: 

Use Match in Regex to split, then output formatted string with match.groups

Regex regex = new Regex(@"(?\d{3})(?\d{3})(?\d{4})");

Match match = regex.Match(phone);

if (match.Success) return "(" + match.Groups["first3chr"].ToString() + ")" + " " + match.Groups["next3chr"].ToString() + "-" + match.Groups["next4chr"].ToString();

A: 
Function FormatPhoneNumber(ByVal myNumber As String)
    Dim mynewNumber As String
    mynewNumber = ""
    myNumber = myNumber.Replace("(", "").Replace(")", "").Replace("-", "")
    If myNumber.Length < 10 Then
        mynewNumber = myNumber
    ElseIf myNumber.Length = 10 Then
        mynewNumber = "(" & myNumber.Substring(0, 3) & ") " &
                myNumber.Substring(3, 3) & "-" & myNumber.Substring(6, 3)
    ElseIf myNumber.Length > 10 Then
        mynewNumber = "(" & myNumber.Substring(0, 3) & ") " &
                myNumber.Substring(3, 3) & "-" & myNumber.Substring(6, 3) & " " &
                myNumber.Substring(10)
    End If
    Return mynewNumber
End Function
Arin
A: 

Guys, question is simple so better provide simple answer possible. The person who has asked the question has clearly mentioned that input is a string "1112224444" and not integer or long or whatsoever, so please don't make any assumptions. Please don't mention any boxing. Regex is too complex and cyptic to use. Why don't someone shows how to use String.Format in this case. Any correct initiative will be appreciated.

Rajib Banerjee
Good call on the community wiki ;)
benjynito
A: 

public string phoneformat(string phnumber) { String phone=phnumber; string countrycode = phone.Substring(0, 3); string Areacode = phone.Substring(3, 3); string number = phone.Substring(6,phone.Length);

phnumber="("+countrycode+")" +Areacode+"-" +number ;

return phnumber; }

Output will be :001-568-895623

-Mak

Mak
A: 

To take care of your extension issue, how about:

string formatString = "###-###-#### ####";
returnValue = Convert.ToInt64(phoneNumber)
                     .ToString(formatString.Substring(0,phoneNumber.Length+3))
                     .Trim();
Larry Smithmier
A: 

This should work:

String.Format("{0:(###)###-####}", Convert.ToInt64("1112224444"));

OR in your case:

String.Format("{0:###-###-####}", Convert.ToInt64("1112224444"));

Vivek Shenoy