文字列を固定長にパディングしたい。簡単な戦略は、文字列と、制限に達するのに十分な数の埋め込み文字を含む変数を作成することです。次に、部分文字列操作を使用して、文字列を目的の長さにトリミングします。文字列がすでに目的の長さ以上である場合は、文字列全体を保持するようにアルゴリズムを少し変更しました。
@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 関数
をご覧ください。テキストを左右に揃えることができます。