批处理文件:函数,创建特定字符的字符串,x次数
问题描述:
请帮助我的脚本不工作。批处理文件:函数,创建特定字符的字符串,x次数
@echo off
echo Printing repeated character
call :printStrings retVal 3 #
echo Returned String: "%retVal%"
PAUSE
:printStrings
(
setlocal EnableDelayedExpansion
set /a "Number=%~2"
rem set /a "counter=60-!Number!"
set "returnStr="
set "repeatChar=%~3"
rem echo Character to repeat: %repeatChar%
FOR /L %%G IN (1,1,!Number!) DO (
set "returnStr=%returnStr%%repeatChar%"
echo Adding character
)
)
(
endlocal
set "%~1=%returnStr%"
rem set "%~1=%repeatChar%"
exit /b
)
我需要通过调用函数打印的时间特定的字符x号,所以如果我做
call :printStrings retVal 3 #
预计产量将
返回的字符串:“###”
答
您使用DelayedExpansion,但不在重要的行。 set "returnStr=%returnStr%%repeatChar%"
将失败,因为%returnStr%和%repeatChar%的扩展完成之前该行将被执行。
将其更改为set "returnStr=!returnStr!!repeatChar!"
,它应该工作
_My脚本不会working_,啊哈,你在iPhone上进行测试,或者您试图在Linux或哪一部分是不工作? – jeb 2012-03-05 09:22:49
即使“添加字符”打印了3次,返回的值也始终为空。 – Zenellie 2012-03-05 09:27:55
http://rosettacode.org/wiki/Repeat_a_string#4DOS_Batch很有趣 – 2015-04-26 08:38:41