Created
January 21, 2016 19:49
-
-
Save MagnusTiberius/cc3d848410c189462306 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[TestClass] | |
public class UnitTest1 | |
{ | |
[TestMethod] | |
public void TestMethod1() | |
{ | |
String s1 = TAMSLib.PhoneNumber.FormatUSA("5031234567"); | |
String s2 = TAMSLib.PhoneNumber.FormatUSA("1(503)1234567"); | |
String s3 = TAMSLib.PhoneNumber.FormatUSA("5031234567x346354"); | |
String s4 = TAMSLib.PhoneNumber.FormatUSA("1(503)1234567x63456"); | |
} | |
} | |
output: | |
(503) 123-4567 | |
+1 (503) 123-4567 | |
(503) 123-4567 x346354 | |
+1 (503) 123-4567 x63456 | |
public class PhoneNumber | |
{ | |
static public string FormatUSA(string input) | |
{ | |
StringBuilder sb = new StringBuilder(); | |
StringBuilder phone = new StringBuilder(); | |
StringBuilder extension = new StringBuilder(); | |
string rv = ""; | |
bool bHasExtension = false; | |
if (input.ToUpper().IndexOf("X") > 0) | |
{ | |
var ext = input.ToUpper().IndexOf("X"); | |
foreach(var c in input) | |
{ | |
if(c.ToString().ToUpper().Equals("X")) | |
{ | |
bHasExtension = true; | |
continue; | |
} | |
if (!bHasExtension) | |
{ | |
phone.Append(c); | |
} | |
else | |
{ | |
extension.Append(c); | |
} | |
} | |
} | |
else | |
{ | |
phone.Append(input); | |
} | |
foreach (var c in phone.ToString()) | |
{ | |
if ("0123456789".IndexOf(c) >= 0) | |
{ | |
sb.Append(c); | |
} | |
} | |
if (sb.Length == 10) | |
{ | |
rv = string.Format("({0}{1}{2}) {3}{4}{5}-{6}{7}{8}{9}", sb[0],sb[1],sb[2],sb[3],sb[4],sb[5],sb[6],sb[7],sb[8],sb[9]); | |
if (bHasExtension) | |
{ | |
rv = string.Format("({0}{1}{2}) {3}{4}{5}-{6}{7}{8}{9} x{10}", sb[0], sb[1], sb[2], sb[3], sb[4], sb[5], sb[6], sb[7], sb[8], sb[9], extension); | |
} | |
} | |
else if (sb.Length == 11) | |
{ | |
rv = string.Format("+{0} ({1}{2}{3}) {4}{5}{6}-{7}{8}{9}{10}", sb[0], sb[1], sb[2], sb[3], sb[4], sb[5], sb[6], sb[7], sb[8], sb[9], sb[10]); | |
if (bHasExtension) | |
{ | |
rv = string.Format("+{0} ({1}{2}{3}) {4}{5}{6}-{7}{8}{9}{10} x{11}", sb[0], sb[1], sb[2], sb[3], sb[4], sb[5], sb[6], sb[7], sb[8], sb[9], sb[10], extension); | |
} | |
} | |
else | |
{ | |
rv = input; | |
} | |
return rv; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment