string 在 vbscript 中带零的 Lpad
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18151811/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Lpad with zero's in vbscript
提问by Yousuf Khan
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 :
我试图用 0 向左填充一个字符串。输出字符串的长度应该是 7。这是我的代码:
inputstr = "38"
in = string(7 - Len(inputStr),0) & inputStr
msgbox in
I'm getting error Expected Statement Please help me Thank You
我收到错误预期声明请帮助我谢谢
回答by Andrej Kireje?
The following code will run 5% faster:
以下代码将运行速度提高 5%:
inputStr = "38"
result = Right("0000000" & inputStr, 7)
msgbox result
回答by Ansgar Wiechers
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
回答by Alex K.
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:
in
是保留字,因此不能用作变量名,您必须传递字符串"0"
而不是整数0
,因此:
inputStr = "38"
result = string(7 - Len(inputStr), "0") & inputStr
msgbox result
回答by Kempes
Function:
功能:
Private Function LPad (str, pad, length)
LPad = String(length - Len(str), pad) & str
End Function
Use:
用:
LPad(12345, "0", 7)