Wednesday, April 22, 2009

A Hidden Gem when it comes to string separation

Most developers based on code I have seen separate strings like so:

for (int i=0; i<someData.Count; i++)
myStringBuilder.AppendFormat("{0},", someData[i]);

Then after constructing this string they need to remove the last separator

myStringBuilder = myStringBuilder.Remove(myStringBuilder.Length-1, 1);

I too have used this concept. However, there is another way to do this that a lot of people didn’t even know existed. The String.Join class; it takes 2 params, the separator and the array.

ArrayList<String> myList = new ArrayList<String>();
for (int i=0; i<someData.Count; i++)
return String.Join(",", myList.ToArray());

This would return a string separated by a comma such as “Text,MoreText,EvenMore,AndLast”

1 comment:

Alex Hoffman said...

Great tip - didn't know that about string.Join.

Creative Commons License
Blogged Information and Code is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 United States License.