windowsstringbatch-file

How do you get the string length in a batch file?


There doesn't appear to be an easy way to get the length of a string in a batch file. E.g.,

SET MY_STRING=abcdefg
SET /A MY_STRING_LEN=???

How would I find the string length of MY_STRING?

Bonus points if the string length function handles all possible characters in strings including escape characters, like this: !%^^()^!.


Solution

  • As there is no built in function for string length, you can write your own function like this one:

    @echo off
    setlocal
    REM *** Some tests, to check the functionality ***
    REM *** An emptyStr has the length 0
    set "emptyString="
    call :strlen result emptyString
    echo %result%
    
    REM *** This string has the length 14
    set "myString=abcdef!%%^^()^!"
    call :strlen result myString
    echo %result%
    
    REM *** This string has the maximum length of 8191
    setlocal EnableDelayedExpansion
    set "long=."
    FOR /L %%n in (1 1 13) DO set "long=!long:~-4000!!long:~-4000!"
    (set^ longString=!long!!long:~-191!)
    
    call :strlen result longString
    echo %result%
    
    goto :eof
    
    REM ********* function *****************************
    :strlen <resultVar> <stringVar>
    (   
        setlocal EnableDelayedExpansion
        (set^ tmp=!%~2!)
        if defined tmp (
            set "len=1"
            for %%P in (4096 2048 1024 512 256 128 64 32 16 8 4 2 1) do (
                if "!tmp:~%%P,1!" NEQ "" ( 
                    set /a "len+=%%P"
                    set "tmp=!tmp:~%%P!"
                )
            )
        ) ELSE (
            set len=0
        )
    )
    ( 
        endlocal
        set "%~1=%len%"
        exit /b
    )
    

    This function needs always 13 loops, instead of a simple strlen function which needs strlen-loops.
    It handles all characters.

    The strange expression (set^ tmp=!%~2!) is necessary to handle ultra long strings, else it's not possible to copy them.