How to combine string [] with string with spaces between

How to parse line [] into a line with spaces between How would you reorganize 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(); } 
+6
source share
3 answers

There is already a method for this:

 String.Join(" ", array) 

This places a space between each element. Please note that if any of your elements is an empty string, you fall into areas adjacent to each other, so you might want to filter them ahead of time, for example:

 String.Join(" ", array.Where(s => !String.IsNullOrEmpty(s))) 
+22
source
 internal string ConvertStringArrayToString(string[] array) { return string.Join(" ", array); } 

Of course, it’s stupid to have a method that just calls another, so you could go all the way and completely remove your method ...

+2
source

Using LINQ Aggregate () Method :

 string result = array.Aggregate((acc, next) => acc + " " + next); 
0
source

Source: https://habr.com/ru/post/903584/


All Articles