user1627901
user1627901

Reputation: 159

Print Array Elements on one line

I'm populating an array variable $array at some point in my code, for example like below

this

is

an

array

varaible

What if, I wanted to print out the array variable like thisisanarrayvariable as one liner

i took the below approach, but i'am not getting any out while the program is hanging

for ($i=0;$i -le $array.length; $i++) { $array[$i] }

obviuosly, i dont want to glue them together like $array[0]+$array[1]+$array[2]..

Hope i can get a better answer.

Upvotes: 12

Views: 50666

Answers (2)

Lance U. Matthews
Lance U. Matthews

Reputation: 16612

Joining array elements with no separator

Use the -join operator...

$array -join ''

...or the static String.Join method...

[String]::Join('', $array)

...or the static String.Concat method...

[String]::Concat($array)

For all of the above the result will be a new [String] instance with each element in $array concatenated together.

Fixing the for loop

Your for loop will output each element of $array individually, which will be rendered on separate lines. To fix this you can use Write-Host to write to the console, passing -NoNewline to keep the output of each iteration all on one line...

for ($i = 0; $i -lt $array.Length; $i++)
{
    Write-Host -NoNewline $array[$i]
}
Write-Host

The additional invocation of Write-Host moves to a new line after the last array element is output.

If it's not console output but a new [String] instance you want you can concatenate the elements yourself in a loop...

$result = ''
for ($i = 0; $i -lt $array.Length; $i++)
{
    $result += $array[$i]
}

The += operator will produce a new intermediate [String] instance for each iteration of the loop where $array[$i] is neither $null nor empty, so a [StringBuilder] is more efficient, especially if $array.Length is large...

$initialCapacity = [Int32] ($array | Measure-Object -Property 'Length' -Sum).Sum
$resultBuilder = New-Object -TypeName 'System.Text.StringBuilder' -ArgumentList $initialCapacity
for ($i = 0; $i -lt $array.Length; $i++)
{
    $resultBuilder.Append($array[$i]) | Out-Null # Suppress [StringBuilder] method returning itself
}
$result = $resultBuilder.ToString()

Upvotes: 23

Joey
Joey

Reputation: 354794

Just use

-join $array

which will glue all elements together.

Upvotes: 5

Related Questions