如何将数组对象转换为字符串?
我试过了:
$a = "This", "Is", "a", "cat"
[system.String]::Join(" ", $a)
没有运气。 PowerShell有哪些不同的可能性?
答案 0 :(得分:244)
$a = 'This', 'Is', 'a', 'cat'
使用双引号(并可选择使用分隔符$ofs
)
# This Is a cat
"$a"
# This-Is-a-cat
$ofs = '-' # after this all casts work this way until $ofs changes!
"$a"
使用operator join
# This-Is-a-cat
$a -join '-'
# ThisIsacat
-join $a
转换为[string]
# This Is a cat
[string]$a
# This-Is-a-cat
$ofs = '-'
[string]$a
答案 1 :(得分:29)
答案 2 :(得分:15)
1> $a = "This", "Is", "a", "cat"
2> [system.String]::Join(" ", $a)
第二行执行操作并输出到主机,但不修改$ a:
3> $a = [system.String]::Join(" ", $a)
4> $a
这是一只猫
5> $a.Count
1
答案 3 :(得分:6)
从管道
# This Is a cat
'This', 'Is', 'a', 'cat' | & {"$input"}
# This-Is-a-cat
'This', 'Is', 'a', 'cat' | & {$ofs='-';"$input"}
写主机
# This Is a cat
Write-Host 'This', 'Is', 'a', 'cat'
# This-Is-a-cat
Write-Host -Separator '-' 'This', 'Is', 'a', 'cat'
答案 4 :(得分:3)
您可以指定类似的类型:
[string[]] $a = "This", "Is", "a", "cat"
检查类型:
$a.GetType()
确认:
IsPublic IsSerial Name BaseType -------- -------- ---- -------- True True String[] System.Array
输出$ a:
PS C:\> $a This Is a cat
答案 5 :(得分:0)
$a = "This", "Is", "a", "cat"
foreach ( $word in $a ) { $sent = "$sent $word" }
$sent = $sent.Substring(1)
Write-Host $sent