批處理指令碼 - 字串長度



在 DOS 指令碼中,沒有定義用於查詢字串長度的長度函式。有一些自定義函式可以用於相同的目的。以下是顯示字串長度的一個自定義函式示例。

示例

@echo off
set str = Hello World
call :strLen str strlen
echo String is %strlen% characters long
exit /b

:strLen
setlocal enabledelayedexpansion

:strLen_Loop
   if not "!%1:~%len%!"=="" set /A len+=1 & goto :strLen_Loop
(endlocal & set %2=%len%)
goto :eof

需要注意關於上述程式的一些關鍵事項 −

  • 查詢字串長度的實際程式碼在 :strLen 塊中定義。

  • 字串的長度儲存在 len 變數中。

輸出

上述命令產生以下輸出。

11
batch_script_strings.htm
廣告