Friday, May 18, 2012

Quick Trick, Splitting on Multiple Characters

This is more of a Junior Varsity post, as I'm sure the .Net gods have figured this technique out a long time ago.  But for the rest of us, if you ever wanted to split a string on more than one character, this is how it is done in .Net, or at least one of possibly many ways it can be done. In this example I want to split on new line breaks and space characters.

string mybiglongstringwithlotsofnewlines = "a whole bunch of characters";
List < char > lst = Environment.NewLine.ToList < char > ;
lst.Add(' ');
string[] myarray = mybiglongstringwithlotsofnewlines.Split(lst.ToArray());

Happy coding!