Get String length - strlen.cmd

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

@echo off
Setlocal EnableDelayedExpansion
:: strLen String [RtnVar]
::             -- String  The string to be measured, surround in quotes if it contains spaces.
::             -- RtnVar  An optional variable to be used to return the string length.
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

If you pass a string to this function surrounded in quotes, it will be able to handle special punctuation characters such as &, > or ^
The surrounding quotes will not be considered in calculating the length.

Source/credits: Dave Benham and others from the DosTips forum (strLen7)

Examples calling strlen.cmd:

@Echo off
Setlocal
Set _demo="hello world"
Call strLen.cmd %_demo%

C:\> 11

Or using a variable for the result:

@Echo off
Setlocal
Set _demo="hello world"
Call strLen.cmd %_demo% _len
Echo length is %_len%

C:\> length is 11

A discussion of this script along with some alternative functions can be found over on the SS64 forum.

“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

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


 
Copyright © SS64.com 1999-2019
Some rights reserved