How can I remove spaces from this PowerShell array?

£可爱£侵袭症+ 提交于 2021-02-11 15:42:14

问题


I'm trying to get all ASCII numbers and letters from Powershell for use as a key later on.

My code so far looks like this:

[char[]] $keyArray = @()
for($i = 65;$i -le 122;$i++) 
{
    if($i -lt 91 -or $i -gt 96)  
    {
        $keyArray += [char]$i
    }  
}
for($i = 0; $i -le 9; $i++)
{
    $keyArray += ("$i")
}

Write-Host [string]$keyArray

However, when I write this out (last line), I get the following with spaces in between each character:

A B C D E F G H I J K L M N O P Q R S T U V W X Y Z a b c d e f g h i j k l m n o p q r s t u v w x y z 0 1 2 3 4 5 6 7 8 9

How can I remove those spaces?


回答1:


You can use -join operator to join array elements. Binary form of that operator allows you to specify custom separator:

-join $keyArray
$keyArray -join $separator

If you really have array of characters, then you can just call String constructor:

New-Object String (,$keyArray)
[String]::new($keyArray) #PS v5

And does not use array addition. It slow and unnecessary. Array operator @() is powerful enough in most cases:

$keyArray = [char[]] @(
    for($i = 65;$i -le 122;$i++)
    {
        if($i -lt 91 -or $i -gt 96)
        {
            $i
        }
    }
    for($i = 0; $i -le 9; $i++)
    {
        "$i"
    }
)

With use of PowerShell range operator you code can be simplified:

$keyArray = [char[]] @(
    'A'[0]..'Z'[0]
    'a'[0]..'z'[0]
    '0'[0]..'9'[0]
)



回答2:


If you want one character per line:

Write-Host ($keyArray | out-string)

If you want all chars on one line:

Write-Host ($keyArray -join '')



回答3:


Use the builtin Output Field Seperator as follows (one-line, use semi-colon to separate, and you MUST cast $keyArray to [string] for this to work):

$OFS = '';[string]$keyArray

Reference



来源:https://stackoverflow.com/questions/34528261/how-can-i-remove-spaces-from-this-powershell-array

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!