给定:$array = ("a0", "a1", "b0", "b1")
我如何只 array[0]
加入& array[1]
; 这样:
$a = "a0a1"
# 好像: >$a = $a[0]$a[1]
同样,
得到:$b = "b0b1"
给定:$array = ("a0", "a1", "b0", "b1")
我如何只 array[0]
加入& array[1]
; 这样:
$a = "a0a1"
# 好像: >$a = $a[0]$a[1]
同样,
得到:$b = "b0b1"
您可以选择数组中的元素,然后使用-join
运算符:
$array = ("a0", "a1", "b0", "b1")
$a = $array[0..1] -join ''
$b = $array[2..3] -join ''
您可以使用逗号来选择不连续的元素。
$array = ("a0", "a1", "b0", "b1")
$c = $array[0,1,3] -join ''
如果您想要加入的元素有一些标准,您可以对数组进行分组,然后加入组。
# Joins all elements that start with the same character.
$array = ("a0", "a1", "b0", "b1")
$a = $array| group {$_[0]}| foreach {$_.group -join ''}
替代解决方案:
$array= ("a1", "a0", "b0", "b1")
$a,$b = &{$ofs='';[string[]]($array[0,1],$array[2,3])}
未经测试,但我认为它应该可以工作:
$array | % {
switch -Regex ($_)
{
('a\d') {$a = "$($a)$($_)"}
('b\d') {$b = "$($b)$($_)"}
}
}