String to array, array to string
February 9, 2011This post is more of a reminder for me than it is some enlightened tutorial. I simply have a mental block when it comes to remembering which methods to use when converting a delimited string into an array and vice versa. Here’s my reminder.
Converting a delimited string into an array
A delimited string can be converted into an array with the String.Split() method. It accepts a character array. You can pass a single character delimiter in single quotes – not double – and the framework will handle it for you.
string commaString = "separated,by,commas,";
string[] arrayOfStrings = commaString.Split(',');
//Result: [separated][by][commas][]
To prevent empty elements, provide the appropriate StringSplitOptions enumeration. Annoyingly, this overload doesn’t work when providing a single character delimiter. It must be provided as a character array.
string commaString = "separated,by,commas,";
char[] delimiter = new char[] { ',' };
string[] arrayOfStrings = commaString.Split(delimiter, StringSplitOptions.RemoveEmptyEntries);
//Result: [separated][by][commas]
When you have a multi-character delimiter, splitting must be done with a string array thusly.
string bracketString = "[separated][by][brackets]";
string[] arrayOfStrings = bracketString.Split(new string[] { "][" }, StringSplitOptions.None);
//Result: [separated][by][brackets]
Converting an array to a delimited string
An array can be converted into a delimited string with the static String.Join() method. It accepts the string you wish to delimit with and an array of strings.
string[] arrayOfStrings = new string[] { "one", "two", "three" };
string delimitedString = string.Join(",", arrayOfStrings);
//Result: "one,two,three"
You can also join an IEnumerable<string>.
List<string> stringList = new List<string>() {"one", "two", "three" };
string delimitedString = string.Join(", ", stringList);
//Result: "one, two, three"
End.
