Thursday, April 2, 2009

Method to Surround Substrings with Single Quotes

If you have a long string containing substrings delimited by commas, you may need to surround each piece with single commas.
For example: trains, planes, automobiles.
In such a case, this method may come in handy:

public static string delimitString(string str){
string[] arr = str.Split(',');
StringBuilder sb = new StringBuilder();
foreach (string s in arr)
{
sb.Append("'" + s.Trim() + "',");
}
sb.Length--;
return sb.ToString();
}

The resulting string will look like this: 'trains', 'planes', 'automobiles'

No comments:

Post a Comment