How to parse string[] to string with spaces in between How would you refactor this code?
internal string ConvertStringArrayToString(string[] array)
{
StringBuilder builder = new StringBuilder();
builder.Append(array[0]);
for (int i = 1; i < array.Length; i++)
{
builder.Append(' ');
builder.Append(array[i]);
}
return builder.ToString();
}
To add a space between the characters of a string, call the split() method on the string to get an array of characters, and call the join() method on the array to join the substrings with a space separator, e.g. str. split(''). join(' ') . Copied!
Array#join() The first parameter to join() is called the separator. By default, the separator is a single comma ',' . You can pass in any separator you want. Separators make Array#join() the preferred choice for concatenating strings if you find yourself repeating the same character over and over again.
Array.prototype.join() The join() method creates and returns a new string by concatenating all of the elements in an array (or an array-like object), separated by commas or a specified separator string. If the array has only one item, then that item will be returned without using the separator.
There is a method for that already:
String.Join(" ", array)
This will put a space between each element. Note that if any of your elements are empty strings, you'll end up with spaces adjacent to each other, so you may want to filter those ahead of time, like this:
String.Join(" ", array.Where(s => !String.IsNullOrEmpty(s)))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With