Lpad with zero's in vbscript

前端 未结 4 1326
死守一世寂寞
死守一世寂寞 2020-12-11 01:48

I\'m trying to pad a string with 0\'s to the left.The length of the output string should be 7. Here\'s my code :

inputstr = \"38\"
in = string(7 - Len(input         


        
相关标签:
4条回答
  • 2020-12-11 02:30

    in is a reserved word so can't be used as a variable name and you must pass a string "0" not an integer 0, so:

    inputStr = "38"
    result = string(7 - Len(inputStr), "0") & inputStr
    
    msgbox result
    
    0 讨论(0)
  • 2020-12-11 02:33

    This function will left-pad an input value to the given number of characters using the given padding character without truncating the input value:

    Function LPad(s, l, c)
      Dim n : n = 0
      If l > Len(s) Then n = l - Len(s)
      LPad = String(n, c) & s
    End Function
    

    Output:

    >>> WScript.Echo LPad(12345, 7, "0")
    0012345
    >>> WScript.Echo LPad(12345, 3, "0")
    12345
    0 讨论(0)
  • 2020-12-11 02:42

    The following code will run 5% faster:

    inputStr = "38"
    result = Right("0000000" & inputStr, 7)
    
    msgbox result
    
    0 讨论(0)
  • 2020-12-11 02:47

    Function:

    Private Function LPad (str, pad, length)
        LPad = String(length - Len(str), pad) & str
    End Function
    

    Use:

    LPad(12345, "0", 7)
    
    0 讨论(0)
提交回复
热议问题