Batch Script - String length


In DOS scripting, there is no length function defined for finding the length of a string. There are custom-defined functions which can be used for the same. Following is an example of a custom-defined function for seeing the length of a string.


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

setlocal enabledelayedexpansion

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

A few key things to keep in mind about the above program are −

  • The actual code which finds the length of string is defined in the :strLen block.

  • The length of the string is maintained in the variable len.


The above command produces the following output.