我有一个字符串数组。例如:
Array[0] = ‘4’
Array[1] = ‘7’
Array[2] = ‘8‘
Array[3] = ‘9‘
Array[4] = ‘10‘
Array[5] = ‘21‘
Array[6] = ‘25‘
Array[7] = ‘26‘
Array[8] = ‘27‘
如何以这种方式对数字进行分组?
Array[0] = “4”
Array[1] = “7..10”
Array[2] = “21”
Array[3] = “25..27”
有powershell功能吗? 坦克!
这是一种方法,请参阅内联注释以遵循逻辑。
$Array = @(
'4'
'7'
'8'
'9'
'10'
'21'
'25'
'26'
'27'
)
$startRange = $null
for ($i = 0; $i -lt $Array.Length; $i++) {
# get the array element
$value = $Array[$i]
# if the next array element is not equal to this array element + 1
if ($Array[$i + 1] -ne $value + 1) {
# and we had captured a sequence before
if ($startRange) {
# output the sequence
"$startRange..$value"
# and reset this variable
$startRange = $null
}
else {
# else, there was no sequence before, output as is
"$value"
}
# and go to next iternation
continue
}
# else, the next array element is equal to this value + 1
if (-not $startRange) {
# capture a start of a sequence
$startRange = $value
}
}