Find first available serial based on list of strings?

后端 未结 4 1112
挽巷
挽巷 2021-01-26 02:34

Given a list of strings such as: apple01, apple02, and apple04, banana02, cherry01, how would you come up with t

4条回答
  •  孤城傲影
    2021-01-26 02:47

    This seems to do the trick!

    ## Create variable to store number in 
    $spareNumber = $null 
    ## we are presuming that they have already been seperated into groups 
    $apples = @("apples01","apples002","apples3","apples15") 
    ## create an empty array 
    $num = @() 
    ## You know what a foreach is right? ;) 
    foreach ($apple in $apples)
    {
        ## the hard working part 
        ## [convert]:: toint32 converts to, you guessed it... (and adds it to $num)
        ## $apple -split ($apple -split '\d+$') < split all digits from end, then strip off everything at the front 
        $num += [convert]::ToInt32([string]$($apple -split ($apple -split '\d+$'))[1], 10)
    }
    ## count from 1 to 10, and pass to foreach 
    (1..10) | foreach {
        ##'when we find one that isn't in $num, store it in sparenumber and break out of this joint. 
        if (!$num.Contains($_)) {
            $spareNumber = $_ 
            break 
        }
     }
     ## and here is your number... 
     $spareNumber 
    

提交回复
热议问题