批量获取变量的长度

时间:2016-12-16 07:34:41

标签: batch-file variables string-length

假设我编写此批处理代码以生成变量

set var1=test

现在我如何获得此变量的长度并回显它?

3 个答案:

答案 0 :(得分:5)

  

函数调用版

见  1. DosTips length of a string

@echo off
set /p "input=Enter text: "
call :strlen "%input%", len
echo Length is %len%
exit/B

:strlen string len
SetLocal EnableDelayedExpansion
set "token=#%~1" & set "len=0"
for /L %%A in (12,-1,0) do (
    set/A "len|=1<<%%A"
    for %%B in (!len!) do if "!token:~%%B,1!"=="" set/A "len&=~1<<%%A"
)
EndLocal & set %~2=%len%
exit/B

How it works

  

宏版

我已经将宏版本包含在内了,虽然可能很难看出它是如何工作的,但实际上它会加速执行,因为它是内联扩展的,不需要函数查找。

见  1. Macros with parameters appended  2. How do you get the string length in a batch file?

@echo off
SetLocal DisableDelayedExpansion
call :setupMacros
set /p "input=Enter text: "
%STRLEN% len,input
echo Length is %len%
EndLocal
exit/B

:setupMacros
set ^"LF=^

^" don't remove previous line     & rem line feed
set ^"\n=^^^%LF%%LF%^%LF%%LF%^^"  & rem newline with line continuation

:: macro definition
:: ------------------------------------------------------------------------------------------------------------------------------------------------------------------------
:: http://www.dostips.com/forum/viewtopic.php?f=3&t=2518

:: get string length
set STRLEN=for %%{ in (1 2) do if %%{==2 (%\n%
  for /F "tokens=1,2 delims=, " %%1 in ("!argv!") do (%\n%
    set "S=A!%%~2!"^&set "L=0"%\n%
    for /L %%A in (12,-1,0) do (set/a "L|=1<<%%A"^&for %%B in (!L!) do if "!S:~%%B,1!"=="" set/a "L&=~1<<%%A")%\n%
    for /F "delims=" %%} in ("!L!") do EndLocal^& set "%%1=%%~}"%\n%
  )%\n%
) else SetLocal EnableDelayedExpansion ^& set argv=,
exit/B 0
  

这些版本总共需要13个循环操作来处理多达8192个   字符串长度。您可以减少循环操作以加速,但每一次   去除的环减少了两个可以处理的长度(即12   loops = 4096,11个循环= 2048,等等)

答案 1 :(得分:1)

您可以使用此代码:

@echo off
setlocal EnableExtensions EnableDelayedExpansion
set "var1=test"
set "Length=0"
if not defined var1 goto OutputLength
:GetLength
if not "!var1:~%Length%,1!" == "" (
    set /A Length+=1
    goto GetLength
)
:OutputLength
echo Length of variable var1 is: %Length%
endlocal
pause

要了解使用的命令及其工作原理,请打开命令提示符窗口,执行以下命令,并完全阅读为每个命令显示的所有帮助页面。

  • echo /?
  • endlocal /?
  • goto /?
  • if /?
  • pause /?
  • set /?
  • setlocal /?

答案 2 :(得分:-1)

如果您将变量回显到文件然后获取文件的长度,则可以因为不可见的字符而减去2个字符。

echo %var1%> length.txt
for %%? in (length.txt) do ( set /a length=%%~z? - 2 )

那么你的长度应该是一个名为“ length ”的变量