string bar = "this is some&string&to be split";
char[] foo = new char[1];
foo[1] = '&';
string[] splitString = bar.Split(foo);
Digging into the documentation on string.Split() you find that there are two versions:
public string[] Split(char[], int);
and
public string[] Split(params char[]);The second is of interest to us because of the 'params' keyword. Those of you familiar with the Console.WriteLine() call (or printf() from the old C days) will recognize that 'params' allows us to supply a parameter list of unknown size and pass it into a function. In this case, the Split() call can be made with a single '&' parameter instead of making it into an array. So we get the following:
string bar = "this is some&string&to be split";
string[] splitString = bar.Split('&');
Also note that if we needed to add another character to split on, say a space, we would write the split like this:
string[] splitString = bar.Split('&', ' ');
Simple, elegant and more in touch with your C# self :)
No comments:
Post a Comment