Created
April 4, 2017 20:56
-
-
Save hudsonmendes/5b531297d2ac6e0c13a066f0670d64fc to your computer and use it in GitHub Desktop.
PhoneNumberFormatter.cs (Broken)
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
using System.Text.RegularExpressions; | |
namespace Sample | |
{ | |
public class PhoneNumberFormatter | |
{ | |
private readonly string number; | |
public PhoneNumberFormatter(string number) | |
{ | |
this.number = number; | |
} | |
public string Format() | |
{ | |
if (string.IsNullOrWhiteSpace(number)) { return string.Empty; } | |
var cleanNumber = Regex.Replace(number, "[^0-9]", string.Empty); | |
var maxPositions = 10; | |
var formattedPosition = maxPositions; | |
var formattedChars = new char[maxPositions + 1]; | |
var first = true; | |
for (var i = (cleanNumber.Length - 1); i >= 0; i--) | |
{ | |
var isLocusBreaker = (cleanNumber.Length - (i + 1)) % 4 == 0; | |
if (isLocusBreaker && !first) { formattedChars[formattedPosition--] = '-'; } | |
if (first) { first = false; } | |
formattedChars[formattedPosition--] = cleanNumber[i]; | |
} | |
for (var i = 0; i < formattedChars.Length; i++) | |
{ | |
if (formattedChars[i] == '\0') | |
{ | |
formattedChars[i] = ' '; | |
} | |
} | |
return new string(formattedChars).Trim(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment