0

在 Powershell 中,如何将具有不同长度字符的字符串转换为格式化为每个项目特定字符数的数组?使用数组中每个项目 10 个字符的示例:

string: 012345678901234567890123456789

array:

0123456789
0123456789
0123456789

所以数组中的第一项将是字符串的前 10 个字符,第二项是接下来的 10 个字符,依此类推。谢谢。

4

2 回答 2

2
$num = '012345678901234567890123456789123' #Lenght is 33
#$num = '012345678901234567890123456789' #Lenght is 30
$split = 10
$len = $num.Length

$repeat=[Math]::Floor($len/$split)

for($i=0;$i-lt$repeat;$i++){
    #$num[($i*$split)..($i*$split+$split-1)]
    Write-Output (($num[($i*$split)..($i*$split+$split-1)]) -join '')
}
if($remainder=$len%$split){
    #$num[($len-$remainder)..($len-1)]
    Write-Output (($num[($len-$remainder)..($len-1)]) -join '')
}

希望这可以帮助

甚至更好地将其变成一个可重复使用的函数,如下所示:

function Split-ByLength{
    <#
    .SYNOPSIS
    Splits string up by Split length.

    .DESCRIPTION
    Convert a string with a varying length of characters to an array formatted to a specific number of characters per item.

    .EXAMPLE
    Split-ByLength '012345678901234567890123456789123' -Split 10

    0123456789
    0123456789
    0123456789
    123

    .LINK
    http://stackoverflow.com/questions/17171531/powershell-string-to-array/17173367#17173367
    #>

    [cmdletbinding()]
    param(
        [Parameter(ValueFromPipeline=$true)]
        [string[]]$InputObject,

        [int]$Split=10
    )
    begin{}
    process{
        foreach($string in $InputObject){
            $len = $string.Length

            $repeat=[Math]::Floor($len/$Split)

            for($i=0;$i-lt$repeat;$i++){
                #Write-Output ($string[($i*$Split)..($i*$Split+$Split-1)])
                Write-Output $string.Substring($i*$Split,$Split)
            }
            if($remainder=$len%$split){
                #Write-Output ($string[($len-$remainder)..($len-1)])
                Write-Output $string.Substring($len-$remainder)
            }
        }        
    }
    end{}
}

$num1 = '012345678901234567890123456789' #Lenght is 30
$num2 = '012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789123123' #Lenght is 33

Split-ByLength -InputObject $num2 -Split 10
于 2013-06-18T15:49:32.790 回答
2

这是一种方法:

$a = '012345678901234567890123456789'

if($a.length % 10)
{
    for($i=0; $i -lt $a.length; $i+=10)
    {
        $a.Substring($i,10)    
    }
}
else
{
    "String length must devide in 10 without a remainder"
}

另一种方式:

if($a.length % 10)
{
    0..2 | Foreach {$a.Substring(($_*10),10)}
}
else
{
    "String length must devide in 10 without a remainder"
}
于 2013-06-18T14:37:48.777 回答