12

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.

2 Answers 2

23

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()
Sign up to request clarification or add additional context in comments.

4 Comments

used the join without any luck
What did you try? And what was the result?
My bad..My earlier comment was without using the -join $array and [string]$srray, but with [string]$array i'am getting spaces in between elements
-join ',' to retrieve an array in CSV format. For quoted CSV: $inner = $tokens -join '","'; $output = """$inner"""; $output
5

Just use

-join $array

which will glue all elements together.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.