Suppose I write this batch code to make a variable
set var1=test
Now how would I get the length of this variable and echo it?
Suppose I write this batch code to make a variable
set var1=test
Now how would I get the length of this variable and echo it?
Function call version
see 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
Macro version
I have included the macro version as, though it may be hard to see how it works, indeed it speeds up execution as it is expanded inline, no function lookup is needed.
see 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
These versions need always 13 loop operations to handle up to 8192 chars string length. You may reduce loop operations to speed up, but every loop removed reduce by two the length that can be handled (i.e 12 loops=4096, 11 loops=2048, and so on)
There could be used this code:
@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
To understand the commands used and how they work, open a command prompt window, execute there the following commands, and read the displayed help pages for each command, entirely and carefully.
echo /?
endlocal /?
goto /?
if /?
pause /?
set /?
setlocal /?
If you echo the variable to a file and then get the length of the file, you can subtract 2 characters because of invisible characters.
echo %var1%> length.txt
for %%? in (length.txt) do ( set /a length=%%~z? - 2 )
Then your length should be in a variable called "length"