Skip to content

Instantly share code, notes, and snippets.

@hudsonmendes
Created April 4, 2017 20:56
Show Gist options
  • Save hudsonmendes/5b531297d2ac6e0c13a066f0670d64fc to your computer and use it in GitHub Desktop.
Save hudsonmendes/5b531297d2ac6e0c13a066f0670d64fc to your computer and use it in GitHub Desktop.
PhoneNumberFormatter.cs (Broken)
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