Batch Script - String length


Advertisements

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.

Example

@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

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.

Output

The above command produces the following output.

11
batch_script_strings.htm
Advertisements