Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I reverse a string in Batch?

I found this solution for reversing strings that worked before, but not any more for some reason:

setlocal enabledelayedexpansion
set num=0
:LOOP
call set tmpa=%%advanced:~%num%,1%%%
set /a num+=1
if not "%tmpa%" equ "" (
set string1=%tmpa%%string1%
goto LOOP
)

My message that I receive is:

The input line is too long.
The syntax of the command is incorrect.

I simply need to reverse the string in the variable %advanced% and output it to %string1%.

If reversing strings can be done in one line, that would be super helpful in the project I am working on. If it can be done without the setlocal enabledelayedexpansion, that would be even more helpful but I doubt it is be possible.

like image 442
DragonZeith Avatar asked Dec 07 '25 01:12

DragonZeith


2 Answers

Another way using a BAT/VBS :

@echo off
set "advanced=1234567890"

echo WScript.Echo StrReverse("%advanced%"^) >reverse.vbs

for /f "delims=" %%a in ('cscript //nologo reverse.vbs') do set "$reversed=%%a"
>nul del reverse.vbs

echo reversed string --^> %$reversed%
like image 146
SachaDee Avatar answered Dec 09 '25 19:12

SachaDee


In this way it works if you change to set string1=!tmpa!!string1!

@echo off
setlocal enabledelayedexpansion
set "advanced=abcdefghijklmnopqrstuvwxyz!"

set "num=0"
:LOOP
call set "tmpa=%%advanced:~%num%,1%%%"
set /a num+=1
if not "%tmpa%" equ "" (
  set "string1=!tmpa!!string1!"
  goto LOOP
)
echo !string1!
endlocal

Another way a bit faster:

@echo off
setlocal enabledelayedexpansion
set "advanced=abcdefghijklmnopqrstuvwxyz"
echo %advanced%>"%tmp%\alpha.tmp"

for %%l in ("%tmp%\alpha.tmp") do set /a len=%%~zl
set /a len-=2

set "reverse="
set "char="
for /l %%i in (0,1,%len%) do (
  for /f "usebackq" %%a in ("%tmp%\alpha.tmp") do (
    set "char=%%a"
    set "reverse=!char:~%%i,1!!reverse!"
  )
)
del "%tmp%\alpha.tmp"
echo !reverse!
endlocal
like image 39
Paul Avatar answered Dec 09 '25 19:12

Paul



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!