Thursday, 12 March 2015

Function Accumulate the Number at the End of the String

Hi there, sorry it’s been a bit quiet on the blog recently, had my head stuck in something big...

Here’s a useful PowerShell function for something I was writing. A few examples of the outputs:

ABCD   --- output ---> ABCD1
ABCD1  --- output ---> ABCD2
999    --- output ---> 1000
ABC999 --- output ---> ABC1000

The function is below (I’m sure there’s a much more elegant way of doing this):

Function AccumulateNumberAtEndOfString {

  Param([String]$InString)
      
  [Int]$Pointer             = $InString.Length -1
  [Boolean]$EndsWithNumber  = $False
  [Boolean]$Result          = $False    
      
  while (!$Result){ 
    If($InString.Substring($Pointer,1) -match "^[0-9]+$") {
      $EndsWithNumber = $True
      $Pointer--
    } else {
      $Result = $True
    }
    If ($Pointer -lt 0){$Result = $True}              
  }
      
  If ($EndsWithNumber) {  
    $InputChars  = $InString.Substring(0,$Pointer + 1)
    $InputNumber = [Int64]$InString.Substring($Pointer +1, $InString.Length - $Pointer - 1)
    $InputNumber ++
    Return ($InputChars + [String]$InputNumber)
  } else {
    Return ($InString + "1")
  }

}

No comments:

Post a Comment