How-to: Get the length of a String - strlen.cmd

This function can be used to return the length of a string.

goto:eof
:strlen  StrVar  [RtnVar]
  setlocal EnableDelayedExpansion
  set "s=#!%~1!"
  set "len=0"
  for %%N in (4096 2048 1024 512 256 128 64 32 16 8 4 2 1) do (
    if "!s:~%%N,1!" neq "" (
      set /a "len+=%%N"
      set "s=!s:~%%N!"
    )
  )
  endlocal&if "%~2" neq "" (set %~2=%len%) else echo %len%
exit /b

Copy the function above to the end of your batch file and then call it like this:

Set "_demo=some example string"
Call :strlen _demo _length
Echo String is %_length% characters long

Source/credits: Dave Benham and others from the DosTips forum see SS64 forum thread with some alternative string length functions.

“You can't do anything about the length of your life, but you can do something about its width and depth” ~ Henry Louis Mencken

Related commands:

How-to: VarSubstring - Extract part of a variable (substring)
How-to: VarSearch - Search & replace part of a variable.


 
Copyright © 1999-2022 SS64.com
Some rights reserved