Skip to content

Instantly share code, notes, and snippets.

@davidruhmann
Created December 18, 2012 02:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davidruhmann/4324449 to your computer and use it in GitHub Desktop.
Save davidruhmann/4324449 to your computer and use it in GitHub Desktop.
setlocal
set "myString=abcdef!%%^^()^!"
call :strlen result myString
echo %result%
goto :eof
:strlen <resultVar> <stringVar>
(
setlocal EnableDelayedExpansion
set "s=!%~2!#"
set "len=0"
for %%P in (4096 2048 1024 512 256 128 64 32 16 8 4 2 1) do (
if "!s:~%%P,1!" NEQ "" (
set /a "len+=%%P"
set "s=!s:~%%P!"
)
)
)
(
endlocal
set "%~1=%len%"
exit /b
)
:: Returns the string length.
:: PARAM
:: 1 String string to get length of
:: RETURN Integer string length
:STRLEN
SETLOCAL ENABLEEXTENSIONS ENABLEDELAYEDEXPANSION
SET STR="%~1"& SET STR=!STR:~1,-1!
SET LEN=0
:: Max string length is 8191, see http://support.microsoft.com/kb/830473
SET POS=8192
:STRLEN_LOOP
SET /A POS /= 2
IF NOT "!STR!" == "" (
IF NOT "!STR:~%POS%,1!" == "" (
SET /A LEN += %POS% + 1
:: work on rest, that is after POS+1
SET STR=!STR:~%POS%!
SET STR=!STR:~1!
)
GOTO :STRLEN_LOOP
)
ENDLOCAL & SET RESULT=%LEN%
GOTO :EOF
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment