Make this code run on first character

2019-08-12 10:03发布

问题:

I was given some batch code that takes a variable and converts it to uppercase characters. ie, joshua will become JOSHUA. I've been reading the documentation for the commands used and I cannot work out quite how the code works, but I would like to amend the code so it only capitalizes the first character. ie, joshua to Joshua. I assume it is just a matter of modifying the 'loop' (?) that the code uses. Any help or advice appreciated.

Code -

 :toUpper str -- converts lowercase character to uppercase
 if not defined %~1 EXIT /b
 for %%a in ("a=A" "b=B" "c=C" "d=D" "e=E" "f=F" "g=G" "h=H" "i=I"
        "j=J" "k=K" "l=L" "m=M" "n=N" "o=O" "p=P" "q=Q" "r=R"
        "s=S" "t=T" "u=U" "v=V" "w=W" "x=X" "y=Y" "z=Z" "ä=Ä"
        "ö=Ö" "ü=Ü") do (
call set %~1=%%%~1:%%~a%%
)
EXIT /b

Note: I could not find any reference to the meaning of the multiple % signs in the SET help documentation. I am guessing this is where the key to the problem lies.

Cheers

EDIT: If someone could give a very brief explanation of what is going on in the code that would be fantastic also! The only part I understand is it is substituting the lower case letters for an uppercase letter

回答1:

Capitalizing first letter will require different approach:

@echo off


set "name=npocmaka"
echo before firstToUpper - %name%

call ::firstToUpper name

echo after firstToUpper - %name%
exit /b 0


:firstToUpper var
setlocal enableDelayedExpansion
set "name=!%~1!"

set first_letter=%name:~0,1%
set last_letters=%name:~1%

for %%# in (A B C D E F G H I J K L M N O P Q R S T U V W X Y Z) do (
    set first_letter=!first_letter:%%#=%%#!
)

set "name=%first_letter%%last_letters%"

endlocal && (
    set "%~1=%name%"
)
exit /b %errorlevel%

To understand this you might need to look at delayed expansion, variable substring , string replacement. Notice that when replacing search of the letter is not case sensitive but replacement itself is