Tuesday, September 8, 2009

.Net method to format phone numbers

public string formatPhone(string phone) { // strips nonnumeric characters from string string strPhone = System.Text.RegularExpressions.Regex.Replace(phone, "\\D", ""); if (strPhone.Length != 10) { return "failed"; } else { try { Int64 iPhone = Convert.ToInt64(strPhone); return ("(" + Convert.ToString(strPhone).Substring(0, 3) + ")" + Convert.ToString (strPhone).Substring(3, 3) + "-" + Convert.ToString(strPhone).Substring(6, 4)); } catch { return "failed"; } } }

No comments:

Post a Comment