NOTE: See A better way to determine the length of a string.


In tip 4193, we determined the length of a string.

I have scripted VarLen.bat, which determines the length of a string by using a file systems objects size attribute.

The syntax fro using VarLen.bat is:

call VarLen VarName Length

where VarName is the name of the variable that contains the string, and Length is a call directed numeric environment variable that will contain the length of the string.

Example:

If you script:

set string=A B C
call VarLen string len
@echo %len%

the echo will display

5

VarLen.bat contains:

@echo off
if \{%2\}==\{\} @echo Syntax: call VarLen VarName Length&goto :EOF
if not defined %1 @echo Syntax: call VarLen VarName Length, VarName not defined.&goto :EOF
set /a %2 = 0
call echo.%%%1%%>%TEMP%\$VarLen$.tmp
for %%n in (%TEMP%\$VarLen$.tmp) do set/a %2 = %%~zn - 2
del /q %TEMP%\$VarLen$.tmp

NOTE: I subtracted 2 from the size to account for:

- The 1 byte CR (Carriage Return.)
- The 1 byte LF (Line Feed).