What is the fastest way to format a string using the US phone format [(XXX) XXX-XXXX] using c#?
My source format is a string.
Not the fastest way, but you can use Extension Methods (note that the parameter must be cleaned up of any previous phone format):
public static class StringFormatToWhatever
{
public static string ToPhoneFormat(this string text)
{
string rt = "";
if (text.Length > 0)
{
rt += '(';
int n = 1;
foreach (char c in text)
{
rt += c;
if (n == 3) { rt += ") "; }
else if (n == 6) { rt += "-"; }
n++;
}
}
return rt;
}
}
Then, use it as
myString.ToPhoneFormat();
Modify to your needs if you want to:
You can also use this to format the string in each user input.