Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to combine string[] to string with spaces in between

Tags:

c#

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();
    }
like image 797
user829174 Avatar asked Dec 12 '11 12:12

user829174


People also ask

How to add space between concatenated strings javascript?

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!

How do you concatenate two strings with a comma?

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.

How to concatenate elements of an array in javascript?

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.


1 Answers

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))) 
like image 165
Guffa Avatar answered Oct 09 '22 08:10

Guffa