看这个十年前的老帖 http://www.bathome.net/thread-11799-1-1.html 可见当年批处理计算字符串长度的"技法峰值"
在此分享源网站 https://www.dostips.com 的这段经典代码(见以下代码段),其内还有两枚技术硬核》
一。句式 set "str=a!%~1!" 提高形参 %1 的容错率,一网打尽键盘所有可见字符
二。句式 (endlocal ... set /a %~2=%len%) 令局部变量亡前可续命给全局变量
附加几行代码》针对经典代码的测试/用法 | @echo off | | :[Loop] //测试代码 备注》调用子过程的形参须是变量名 | | set "str=" &set/p str="输入一个字符串获取其长度:" | | if not defined str exit/b | | (call :strLen str sL) | | echo,长度=%sL% | | goto[Loop] | | | | :: 分享计算字符串长度的经典代码如下》 | | :: string [in] - variable name containing the string being measured for length | | :: len [out] - variable to be used to return the string length | | :: Many thanks to 'sowgtsoi', but also 'jeb' and 'amel27' dostips forum users helped making this short and efficient | | :: Created 20081122,changed 20101116,source https://www.dostips.com | | :strLen string len -- returns the length of a string | | ( setlocal enabledelayedexpansion | | set "str=a!%~1!" &rem keep the a up front to ensure we get the length and not the upper bound,it also avoids trouble in case of empty string | | set "len=0" | | for /l %%a in (12,-1,0) do ( | | set /a "len|=1<<%%a" | | for %%b in (!len!) do if "!str:~%%b,1!"=="" set /a "len&=~1<<%%a" | | ) | | ) | | ( endlocal & rem return values | | if "%~2" neq "" set /a %~2=%len% | | ) | | exit /bCOPY |
|