您想将字符串填充到固定长度。简单的策略是创建一个变量,其中包含您的字符串加上足够多的填充字符以达到您的限制。然后使用子字符串操作将字符串修剪为所需的长度。如果它已经大于或等于所需长度,我稍微修改了算法以保留整个字符串。
@echo off
:: Initialize
setlocal enableDelayedExpansion
set maxLen=50
set "pad="
set "div="
for /l %%N in (1 1 %maxLen%) do (
set "pad=!pad!."
set "div=!div!-"
)
set "div=|!div!|"
:: Test the display
pushd "c:\Users\Joel"
call :displayCurrentDirectory
pushd "c:\Users\Joel\Desktop"
call :displayCurrentDirectory
exit /b
:displayCurrentDirectory
setlocal
set "txt=>>!cd!\"
if "!txt:~%maxLen%,1!" equ "" (
set "txt=!txt!!pad!"
set "txt=!txt:~0,%maxLen%!"
)
echo !div!
echo ^|!txt!^|
echo !div!
echo(
exit /b
这是一个版本,它使用多行固定宽度来强制字符串适应分配的水平空间。
@echo off
:: Initialize
setlocal enableDelayedExpansion
set maxLen=15
set "pad="
set "div="
for /l %%N in (1 1 %maxLen%) do (
set "pad=!pad!."
set "div=!div!-"
)
set "div=|!div!|"
:: Test the display
pushd "c:\Users\Joel"
call :displayCurrentDirectory
pushd "c:\Users\Joel\Desktop"
call :displayCurrentDirectory
exit /b
:displayCurrentDirectory
setlocal
echo !div!
set "txt=>>!cd!\"
:loop
if "!txt:~0,%maxLen%!" neq "!txt!" (
echo ^|!txt:~0,%maxLen%!^|
set "txt=!txt:~%maxLen%!"
goto :loop
)
set "txt=!txt!!pad!"
set "txt=!txt:~0,%maxLen%!"
echo ^|!txt!^|
echo !div!
echo(
exit /b
查看改进的 :Format、新的 :FormatVar 和 :FormatColor 函数
,以获得更通用的文本格式例程。它允许文本的左右对齐。