Friday, May 2, 2008

Batch Function for String Padding


::=======================================================
:padStringLeft string width padCharacter
:: author: wwjdcsk
:: -- pads the front of a string with specified characters to the width specified
::=======================================================
:: -- string [in,out] - time to be formatted, mutated
:: -- width [in] - width of resulting string
:: -- character [in,opt] - character to pad with, default is space
SETLOCAL ENABLEDELAYEDEXPANSION
call set inStr=%%%~1%%
set width=%2
set /a width-=1
set pad=%3
if "%pad%"=="" set pad= &::space

for /l %%i in (0,1,%width%) do (
if "!inStr:~%%i,1!"=="" set inStr=%pad%!inStr!
)

( ENDLOCAL & REM -- RETURN VALUES
IF "%~1" NEQ "" SET "%~1=%inStr%"
)
goto :eof



::=======================================================
:padStringRight string width padCharacter
:: author: wwjdcsk
:: -- pads the back of a string with specified characters to the width specified
::=======================================================
:: -- string [in,out] - time to be formatted, mutated
:: -- width [in] - width of resulting string
:: -- character [in,opt] - character to pad with, default is space
SETLOCAL ENABLEDELAYEDEXPANSION
call set inStr=%%%~1%%
set width=%2
set /a width-=1
set pad=%3
if "%pad%"=="" set pad= &::space

for /l %%i in (0,1,%width%) do (
if "!inStr:~%%i,1!"=="" set inStr=!inStr!%pad%
)

( ENDLOCAL & REM -- RETURN VALUES
IF "%~1" NEQ "" SET "%~1=%inStr%"
)
goto :eof

No comments: