我正在尝试创建一个批处理脚本,将字母转换为数字。 但我无法让它区分大小写 - 有什么建议吗?
@ECHO OFF
setlocal
set init="A=1" "a=2" "B=3" "b=4" "C=5" "c=6"
set %init: =&set %
set "nickname= "
set /P "nickname=Enter here: "
set "nickname=%nickname: =%"
if not defined nickname goto :EOF
set "out="
set "nums="
set "sum=0"
:loop
set "char=%nickname:~0,1%"
set "out=%out%%char%"
set /A "code=%char%, sum+=code"
set "nums=%nums%%code%"
set "nickname=%nickname:~1%"
IF DEFINED nickname GOTO :loop
ECHO original: %out%
ECHO converted to: %nums%
pause
因此,如果我输入 Aa,它会转换为 22 - 但应该是 12。 谢谢! :)
我已经搜索并尝试了不同的解决方案来解决在 stackoverflow 上发现的类似问题。 但到目前为止还没有运气。 如果我输入 Aa,它会转换为 22 - 但应该是 12。
可以使用以下代码来完成此任务:
@echo off
setlocal EnableExtensions DisableDelayedExpansion
:UserPrompt
set "Nickname="
set /P "Nickname=Enter nickname: " || goto UserPrompt
rem Remove all double quotes from the entered string.
set "Nickname=%Nickname:"=%"
if not defined Nickname goto UserPrompt
rem Remove all spaces from the entered string.
set "Nickname=%Nickname: =%"
if not defined Nickname goto UserPrompt
set "Original=%Nickname%"
set "Numbers="
:Loop
for %%G in ("A=1" "a=2" "B=3" "b=4" "C=5" "c=6") do for /F "tokens=1,2 delims==" %%I in (%%G) do if "%Nickname:~0,1%" == "%%I" set "Numbers=%Numbers%%%J" & set "Nickname=%Nickname:~1%" & if defined Nickname (goto Loop) else goto OutputResult
set "Nickname=%Nickname:~1%"
if defined Nickname goto Loop
:OutputResult
setlocal EnableDelayedExpansion
echo Original: !Original!
echo Converted to: !Numbers!
endlocal
endlocal
pause
用户输入有输出
"Asterix & Obelix"
:
Original: Asterix&Obelix
Converted to: 14
代码是故障安全且安全的,这意味着独立于用户在提示时输入的内容,Windows命令处理器真正运行批处理文件中编写的命令,并且永远不会因为字符串输入引起的语法错误而退出由用户。
要了解所使用的命令及其工作原理,请打开命令提示符窗口,执行以下命令,并完整、仔细地阅读每个命令显示的帮助页面。
echo /?
endlocal /?
for /?
goto /?
if /?
pause /?
rem /?
set /?
setlocal /?
另请参阅:
将
下面的六行替换为:loop
,并将for %%G in ("A=1" "a=2" "B=3" "b=4" "C=5" "c=6") do for /F "tokens=1,2 delims==" %%I in (%%G) do if "%nickname:~0,1%" == "%%I" set "nums=%nums%%%J" & set "nickname=%nickname:~1%" & if defined nickname (goto loop) else goto OutputResult
替换为ECHO original: %out%
。:OutputResult