Reasons:
1. A string is immutable meaning you can't actually change the string.
2. StringBuilder is easy to implement. Using built-in functions such as Append and Insert makes my life easier!
Here's my sample code that uses StringBuilder
by the way, do not forget to include this namespace: System.Text
/*
* must be in this format: 999-999-9999
*/
public string formatPhone(string phone)
{
StringBuilder retVal = new StringBuilder();
char[] charArrayPhone = phone.Trim().ToCharArray();
foreach(char cap in charArrayPhone)
{
if (isCharacterNumeric(cap))
retVal.Append(cap);
}
//must only use the last 10 characters (numbers)
if (retVal.Length>10)
retVal.Remove(0,retVal.Length - 10);
//insert dashes
if (retVal.Length>4)
retVal.Insert(retVal.Length - 4, "-");
//area code is not supplied
if(retVal.Length>8)
retVal.Insert(retVal.Length - 8, "-");
return retVal.ToString();
}
/*
* must be in this format: 99999 or 99999-9999
*/
public string formatZipcode(string zipcode)
{
StringBuilder retVal = new StringBuilder();
char[] charArrayZip = zipcode.Trim().ToCharArray();
foreach (char caz in charArrayZip)
{
if (isCharacterNumeric(caz))
retVal.Append(caz);
}
//must only use the first 9 characters (numbers)
if (retVal.Length > 9)
retVal.Remove(9, retVal.Length - 9);
//insert dash
if (retVal.Length > 5)
retVal.Insert(5, "-");
return retVal.ToString();
}
private bool isCharacterNumeric(char Character)
{
char[] charArrayNumbers = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
foreach (char can in charArrayNumbers)
{
if (Character == can)
return true;
}
return false;
}
Wednesday, June 4, 2008
Subscribe to:
Post Comments (Atom)
1 comment:
string builders are the bomb!
Post a Comment