在 Powershell 中对数字进行分组

问题描述 投票:0回答:1

我有一个字符串数组。例如:

Array[0] = ‘4Array[1] = ‘7Array[2] = ‘8Array[3] = ‘9Array[4] = ‘10Array[5] = ‘21Array[6] = ‘25Array[7] = ‘26Array[8] = ‘27

如何以这种方式对数字进行分组?

Array[0] = “4Array[1] = “7..10Array[2] = “21Array[3] = “25..27

有powershell功能吗? 坦克!

arrays powershell numbers grouping
1个回答
0
投票

这是一种方法,请参阅内联注释以遵循逻辑。

$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
    }
}
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.