Skip to main content

How to Reverse a String in Batch Script

Reversing the order of characters in a string is a classic programming puzzle. While not a common daily task, it's a great way to demonstrate advanced string manipulation techniques. It might be used for simple obfuscation, solving programming challenges, or checking for palindromes. Batch scripting has no built-in REVERSE() function, so this task requires a clever, character-by-character loop.

This guide will teach you the standard pure-batch method for reversing a string by iterating through it and prepending each character to a new string. You will learn the critical role that delayed expansion plays in this process and see how the entire logic can be encapsulated in a reusable subroutine.

The Challenge: No Native REVERSE() Function

The cmd.exe interpreter is not designed for complex string manipulation. There is no command to reverse a string, so we must build the functionality from scratch. The logic involves treating the string as a sequence of characters, picking them off one by one, and rebuilding the string in the opposite order.

The Core Method: A "Prepend" Loop

The most effective way to reverse a string in pure batch is to loop through the original string and build a new, reversed string by adding each character to the beginning of the result.

The logic:

  1. Start with your original string (e.g., "Hello") and an empty ReversedString.
  2. First iteration: Take the first character ("H") and put it at the start of ReversedString. (ReversedString is now "H").
  3. Second iteration: Take the next character ("e") and put it at the start of ReversedString. (ReversedString is now "eH").
  4. Third iteration: Take the next character ("l") and put it at the start of ReversedString. (ReversedString is now "leH").
  5. Continue until all characters have been processed. The final result will be "olleH".

The Script: A Basic String Reversal

This script implements the "prepend" loop logic.

@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION

SET "Original=Hello World"
SET "Reversed="

ECHO Original String: %Original%

REM Create a temporary variable to hold the string we are processing.
SET "TempString=%Original%"

:Loop
REM Check if there is still anything left in the temporary string.
IF DEFINED TempString (
REM Get the first character of the temporary string.
SET "FirstChar=!TempString:~0,1!"

REM Prepend this character to our result.
SET "Reversed=!FirstChar!!Reversed!"

REM Remove the first character from the temporary string.
SET "TempString=!TempString:~1!"

REM Go back to the start of the loop.
GOTO :Loop
)

ECHO Reversed String: %Reversed%

ENDLOCAL

How the Script Works

  • SETLOCAL ENABLEDELAYEDEXPANSION: This is absolutely essential. The script is modifying and reading variables (TempString and Reversed) inside a loop structure, which requires delayed expansion using exclamation marks (!Var!).
  • SET "TempString=%Original%": We work on a copy so we don't destroy the original string.
  • :Loop: A label that marks the start of our loop.
  • IF DEFINED TempString: This is our loop's exit condition. The loop continues as long as TempString contains characters.
  • SET "FirstChar=!TempString:~0,1!": Extracts the first character of the remaining string.
  • SET "Reversed=!FirstChar!!Reversed!": This is the core "prepend" logic. It builds the new string by putting the latest character at the front.
  • SET "TempString=!TempString:~1!": This "consumes" the original string from left to right by removing the character we just processed.
  • GOTO :Loop: Jumps back to the start to process the next character.

Making it Reusable: A "Reverse" Subroutine

This logic is perfect for a reusable subroutine that can be called to reverse any variable.

@ECHO OFF
SETLOCAL

SET "MyVar=A man, a plan, a canal - Panama"
ECHO Before: %MyVar%

CALL :Reverse MyVar
ECHO After: %MyVar%

GOTO :EOF

:Reverse
SETLOCAL ENABLEDELAYEDEXPANSION
SET "Original=!%1!"
SET "Reversed="
:ReverseLoop
IF DEFINED Original (
SET "FirstChar=!Original:~0,1!"
SET "Reversed=!FirstChar!!Reversed!"
SET "Original=!Original:~1!"
GOTO :ReverseLoop
)
ENDLOCAL & SET "%1=%Reversed%"
GOTO :EOF
note

This powerful pattern allows you to simply CALL :Reverse MyVariableName to modify a variable in your main script.

Common Pitfalls and How to Solve Them

Forgetting DelayedExpansion

This is the number one reason this script will fail. The entire logic depends on being able to read the current, updated value of the variables inside the loop. Without SETLOCAL ENABLEDELAYEDEXPANSION, the script will enter an infinite loop or produce incorrect results.

Handling Special Characters (!, ^, &)

The script is highly vulnerable to special characters.

  • !: The exclamation mark will be consumed by delayed expansion and disappear from the string before it can even be processed.
  • ^, &, |, <, >: These can break the SET commands, causing syntax errors.

Solution: There is no easy pure-batch solution. This algorithm is best suited for simple alphanumeric strings. For complex strings, a call to PowerShell is far more robust.

powershell -Command "$s='!My&String!'; $a=$s.ToCharArray(); [array]::Reverse($a); -join $a"
note

This PowerShell one-liner correctly reverses any string, including special characters.

Practical Example: Checking for a Palindrome

A palindrome is a word or phrase that reads the same forwards and backwards. This script combines the reverse subroutine with some simple string cleaning to check if a phrase is a palindrome.

@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION

SET "Phrase=Race car"
ECHO Original Phrase: !Phrase!

REM --- Step 1: Clean the string (remove spaces, convert to lowercase) ---
SET "Cleaned=!Phrase: =!"
FOR %%L 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 "Cleaned=!Cleaned:%%L=%%L!"
)
ECHO Cleaned: !Cleaned!

REM --- Step 2: Create a copy and reverse it ---
SET "Reversed=!Cleaned!"
CALL :Reverse Reversed
ECHO Reversed: !Reversed!

REM --- Step 3: Compare the cleaned and reversed strings ---
IF "!Cleaned!"=="!Reversed!" (
ECHO Result: It is a palindrome.
) ELSE (
ECHO Result: It is NOT a palindrome.
)

GOTO :EOF

:Reverse
SETLOCAL ENABLEDELAYEDEXPANSION
SET "Original=!%1!"
SET "Reversed="
:ReverseLoop
IF DEFINED Original (
SET "FirstChar=!Original:~0,1!"
SET "Reversed=!FirstChar!!Reversed!"
SET "Original=!Original:~1!"
GOTO :ReverseLoop
)
ENDLOCAL & SET "%1=%Reversed%"
GOTO :EOF

Conclusion

Reversing a string is a classic example of advanced procedural logic in a batch script.

  • The standard method involves a GOTO loop that iteratively prepends each character of the source string to a new result string.
  • This technique is entirely dependent on DelayedExpansion (!Var!) to function correctly.
  • The logic is best encapsulated in a reusable subroutine for clean, modular code.
  • Be aware that this pure-batch method is not reliable for strings containing special characters. For those, a call to PowerShell is the recommended best practice.