当我使用
!=exitcodeAscii!
进行多字符匹配时,它会执行得非常缓慢,我不知道为什么。
set "ascii_str= #$%%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~"
echo %time%
:ascii_multiple
if defined ascii_str (
set "char=!ascii_str:~0,1!"
for /l %%0 in (32, 1, 126) do cmd /c exit %%0 &if "!=exitcodeAscii!" EQU "!char!" echo %%0
set "ascii_str=!ascii_str:~1!"
) else (echo %time% &pause)
goto ascii_multiple
开始时间:11:21:27.00 结束时间:11:22:29.25,大约1分钟。
但是,如果我使用一种新的方法将字符或字符串转换为ASCII:
@echo off &setlocal EnableDelayedExpansion
chcp 1252 >nul
set "ascii_table= #$%%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~"
set "ascii[33]=^!" &set "ascii[34]=""
:main
set /p "string=String:"
call :str_ascii
echo. &goto main
:str_ascii
if defined string (
set "char=!string:~0,1!"
call :char_ascii
set "string=!string:~1!"
) else (exit /b 0)
goto str_ascii
:char_ascii
set /a index=32
if "!char!"=="!ascii[33]!" echo !ascii[33]! = 33 &exit /b 0
if "!char!"=="!ascii[34]!" echo !ascii[34]! = 34 &exit /b 0
if "!char!"=="" exit /b 1
for /l %%0 in (0, 1, 94) do (
if "!char!"=="!ascii_table:~%%0,1!" echo !char! = !index! &exit /b 0
set /a index+=1)
echo cannot find char &exit /b 1
在这个函数中,我可以处理Ascii字符32-126。
在这种情况下,我尝试使用
查找表来提高效率。
我认为执行
!=exitcodeAscii!
需要执行太多命令,因为如果你想找到最后一个字符
~
,你必须执行94次命令。
所以我把所有的Ascii字符都放在一个字符串里,用
!ascii_table:~%%0,1!
来获取Ascii表中的单个字符,并设置/a索引来计算十进制值。
就像逐个设置数组并相互匹配字符一样。
set "ascii[32]= "
...
set "ascii[126]=~"
测试字符串:
!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~
所有字符的运行速度为 19:33:32.19 到 19:33:32.94 - 小于1秒。
如果您想使用小数值来查找字符,也可以更改一些代码:
:main
set /p "enter=Decimal:"
if defined enter set /a dec=%enter% &call :dec_ascii
echo. &goto main
:dec_ascii
set /a index=32
if !dec!==33 echo !ascii[33]! &exit /b 0
if !dec!==34 echo !ascii[34]! &exit /b 0
if not defined dec exit /b 1
for /l %%0 in (0, 1, 94) do (
if !dec!==!index! echo !ascii_table:~%%0,1! &exit /b 0
set /a index+=1)
echo cannot find char &exit /b 1