gpt4 book ai didi

windows - windows批处理文件中的字符串处理: How to pad value with leading zeros?

转载 作者:可可西里 更新时间:2023-11-01 12:12:32 26 4
gpt4 key购买 nike

在 Windows cmd 批处理文件 (.bat) 中,我如何填充数值,以便将 0..99 范围内的给定值转换为“00”到“99”范围内的字符串。 IE。我想为小于 10 的值设置前导零。

最佳答案

您可以使用一个两阶段过程:

REM initial setup
SET X=5

REM pad with your desired width - 1 leading zeroes
SET PADDED=0%X%

REM slice off any zeroes you don't need -- BEWARE, this can truncate the value
REM the 2 at the end is the number of desired digits
SET PADDED=%PADDED:~-2%

现在 PADDED 保存填充后的值。如果 X 的初始值有可能超过 2 位数,您需要检查您是否不小心截断了它:

REM did we truncate the value by mistake? if so, undo the damage
SET /A VERIFY=1%X% - 1%PADDED%
IF NOT "%VERIFY%"=="0" SET PADDED=%X%

REM finally update the value of X
SET X=%PADDED%

重要提示:

此解决方案创建或覆盖变量 PADDEDVERIFY。任何设置变量值的脚本都不应在终止后保留,应将其放入 SETLOCALENDLOCAL 语句中,以防止这些更改从外部可见世界。

关于windows - windows批处理文件中的字符串处理: How to pad value with leading zeros?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13398545/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com