How to count the characters in a string with Batch? [closed]

我是研究僧i 提交于 2019-11-28 14:22:14

A simple way is to use a function

@echo off
set "myVar=abcdefg"
call :Stringlength result myVar
echo %result%
exit /b

:Stringlength <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
)

This can measure the string to a maximum of 8192 characters, as the maximum size of a string is 8191 bytes, this should be enough.
The first parenthesis blocks is only for a bit more performance.
The second block is needed to return the %len% value behind the endlocal barrier.
The main idea is a binary search, in the first loop the temporary copy in s of the string is tested if it is longer than 4096 bytes or not.
Then the next test will be with 2048 or 6144 (=2048+4096), so the len variable will be at each loop a little bit more exact.
After 13 loops the len is exact.

For faster strlen functions you could read strlen boosted, which uses some more tricks.

There is also a solution with batch macros, macros are normally much faster than functions in batch.

@echo off
call :loadMacros
set "myVar=abcdefg"
%$strlen%  result myVar
echo %result%
exit /b


:loadMacros
set LF=^


::Above 2 blank lines are required - do not remove
set ^"\n=^^^%LF%%LF%^%LF%%LF%^^"
:::: StrLen pResult pString
set $strLen=for /L %%n in (1 1 2) do if %%n==2 (%\n%
        for /F "tokens=1,2 delims=, " %%1 in ("!argv!") do (%\n%
            set "str=A!%%~2!"%\n%
              set "len=0"%\n%
              for /l %%A in (12,-1,0) do (%\n%
                set /a "len|=1<<%%A"%\n%
                for %%B in (!len!) do if "!str:~%%B,1!"=="" set /a "len&=~1<<%%A"%\n%
              )%\n%
              for %%v in (!len!) do endlocal^&if "%%~b" neq "" (set "%%~1=%%v") else echo %%v%\n%
        ) %\n%
) ELSE setlocal enableDelayedExpansion ^& set argv=,

exit /b

At dostips.com are some discussion about the macro technic
1 Batch "macros" with arguments
2 macros with appended parameters

When you call the function, the 2nd parameter should be a value rather than a reference:

call :Stringlength result %myVar%
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!