PowerShell Script to Reverse a String Easily
Use
-join ($string.ToCharArray()[-1..-($string.Length)]) to reverse a string in PowerShell, for example: $reversed = -join ($string.ToCharArray()[-1..-($string.Length)]).Examples
Inputhello
Outputolleh
InputPowerShell
OutputllehSrewoP
Input
Output
How to Think About It
To reverse a string, think of it as flipping the order of its characters. You can convert the string into an array of characters, then read that array backward and join the characters back into a string.
Algorithm
1
Get the input string.2
Convert the string into an array of characters.3
Reverse the order of the characters in the array.4
Join the reversed characters back into a single string.5
Return or print the reversed string.Code
powershell
$string = "PowerShell" $reversed = -join ($string.ToCharArray()[-1..-($string.Length)]) Write-Output $reversed
Output
llehSrewoP
Dry Run
Let's trace reversing the string 'hello' through the code
1
Convert string to array
'hello' becomes ['h','e','l','l','o']
2
Reverse array using index range
Select characters from last to first: ['o','l','l','e','h']
3
Join reversed array
Join characters to form 'olleh'
| Index | Character |
|---|---|
| 4 | o |
| 3 | l |
| 2 | l |
| 1 | e |
| 0 | h |
Why This Works
Step 1: Convert string to array
Using ToCharArray() splits the string into individual characters so we can reorder them.
Step 2: Reverse the array
Using the index range [-1..-($string.Length)] selects characters from the end to the start.
Step 3: Join characters
The -join operator combines the reversed characters back into a single string.
Alternative Approaches
Using [array]::Reverse()
powershell
$array = $string.ToCharArray()
[array]::Reverse($array)
$reversed = -join $array
Write-Output $reversedThis method modifies the array in place and is clear but requires extra steps.
Using a for loop
powershell
$reversed = "" for ($i = $string.Length - 1; $i -ge 0; $i--) { $reversed += $string[$i] } Write-Output $reversed
This manual approach is easy to understand but less efficient for long strings.
Complexity: O(n) time, O(n) space
Time Complexity
Reversing requires visiting each character once, so time grows linearly with string length.
Space Complexity
An extra array of characters is created, so space also grows linearly with string length.
Which Approach is Fastest?
Using -join with a reversed array is concise and efficient; the in-place [array]::Reverse() is similar but requires more lines.
| Approach | Time | Space | Best For |
|---|---|---|---|
| -join with reversed range | O(n) | O(n) | Concise and readable |
| [array]::Reverse() | O(n) | O(n) | In-place array reversal |
| For loop concatenation | O(n^2) | O(n) | Simple logic but slower for long strings |
Use
-join with a reversed character array for a concise string reversal.Beginners often try to reverse the string directly without converting it to a character array first.