DotnetSparrow
DotnetSparrow

Reputation: 27996

formatting string/phone number

I want to format the phone numbers using C#. Format is (XX) YYY-ZZZZ or(XXX) YYY-ZZZZ. So, I need to format the right seven digits and then remaining two or three for area code.

{EDIT}

Phone is saved as a plain string /VARChar of length 9 or 10

Please suggest solution.

Thanks.

Upvotes: 4

Views: 5834

Answers (5)

underscore
underscore

Reputation: 772

static string FormatPhoneNumber( string phoneNumber ) {

   if ( String.IsNullOrEmpty(phoneNumber) )
      return phoneNumber;

   Regex phoneParser = null;
   string format     = "";

   switch( phoneNumber.Length ) {

      case 5 :
         phoneParser = new Regex(@"(\d{3})(\d{2})");
         format      = "$1 $2";
       break;

      case 6 :
         phoneParser = new Regex(@"(\d{2})(\d{2})(\d{2})");
         format      = "$1 $2 $3";
       break;

      case 7 :
         phoneParser = new Regex(@"(\d{3})(\d{2})(\d{2})");
         format      = "$1 $2 $3";
       break;

      case 8 :
         phoneParser = new Regex(@"(\d{4})(\d{2})(\d{2})");
         format      = "$1 $2 $3";
       break;

      case 9 :
         phoneParser = new Regex(@"(\d{4})(\d{3})(\d{2})(\d{2})");
         format      = "$1 $2 $3 $4";
       break;

      case 10 :
         phoneParser = new Regex(@"(\d{3})(\d{3})(\d{2})(\d{2})");
         format      = "($1) $2 $3 $4";
       break;

      case 11 :
         phoneParser = new Regex(@"(\d{4})(\d{3})(\d{2})(\d{2})");
         format      = "($1) $2 $3 $4";
       break;

      default:
        return phoneNumber;

   }//switch

   return phoneParser.Replace( phoneNumber, format );

}//FormatPhoneNumber

Upvotes: 0

Nicholas Carey
Nicholas Carey

Reputation: 74177

Is the phone number stored as a string or a numeric value. If it's stored as an integral value, this should do it:

string formattedPhone = rawNumber.ToString( "(#00) 000-0000" ) ;

If it's stored as a string, you'll need to look at the length and start chopping it up, thus:

static string FormatAsPhoneNumber( string s )
{
  if ( s == null ) throw new ArgumentNullException() ;
  if ( s.Length > 10 ) throw new ArgumentOutOfRangeException() ;

  StringBuilder sb = new StringBuilder() ;
  int           p  = 0 ;
  int           remaining = s.Length ;

  if ( remaining > 7 )
  {
    int areaCodeLength = remaining - 7 ;

    sb.Append("(").Append(s.Substring(p,areaCodeLength)).Append(") ") ;

    p         += areaCodeLength ;
    remaining -= areaCodeLength ;

  }
  if ( remaining > 4 )
  {
    int exchangeLength = remaining - 4 ;

    sb.Append(s.Substring(p,exchangeLength)).Append("-") ;

    p         += exchangeLength ;
    remaining -= exchangeLength ;

  }

  sb.Append(s.Substring(p) ) ;

  string formatted = sb.ToString() ;
  return formatted ;
}

Results:

Raw         Formatted
---------- --------------
1          1
12         12
123        123
1234       1234
12345      1-2345
123456     12-3456
1234567    123-4567
12345678   (1) 234-5678
123456789  (12) 345-6789
1234567890 (123) 456-7890

Upvotes: 1

FlyingStreudel
FlyingStreudel

Reputation: 4464

This will take any string and starting from the right side place up to the first 10 numbers into a

(?xxx) xxx-xxxx

formatted string.

    public string FormatPhone(string input)
    {
        List<char> chars = new List<char>();
        if (input.Length < 9) throw new ArgumentException("Not long enough!");
        for (int i = input.Length - 1; i >= 0; i--)
        {
            if (Char.IsNumber(input[i])) chars.Add(input[i]);
            switch (chars.Count)
            {
                case 4:
                    chars.Add('-');
                    break;
                case 8:
                    chars.Add(' ');
                    chars.Add(')');
                    break;
                case 13:
                    i = 0;
                    break;
            }
        }
        chars.Add('(');
        chars.Reverse();
        return new string(chars.ToArray());
    }

Upvotes: 1

Erick Petrucelli
Erick Petrucelli

Reputation: 14872

If I understood right, you want a function that receives an int and returns a string with the fone number on that format. If so you can do something like:

public string GetPhoneNumber(int number) {
    string n = number.ToString();
    if (n.Length == 9)
        return "(" + n.Substring(0, 2) + ") " + n.Substring(2, 3) + "-" + n.Substring(5, 4);
    else
        return "(" + n.Substring(0, 3) + ") " + n.Substring(3, 3) + "-" + n.Substring(6, 4);
}

Upvotes: 2

Jackson Pope
Jackson Pope

Reputation: 14640

Assuming the phone number is stored as a long, and is either 9 or 10 digits you can do this:

if (number > 999999999L)
{
     return String.Format("{0:(###) ###-####}", number);
}
else
{
     return String.Format("{0:(##) ###-####}", number);
}

Of course this only works if the number is exactly 9 or 10 digits long.

Upvotes: 1

Related Questions