Visit the reverse-string exercise on Exercism to read the full instructions and download the exercise files.
Dig Deeper
built-in reverse
Using reverse built-in method
function ReverseString([string] $String) {
$charArray = $String.ToCharArray()
[Array]::Reverse($charArray)
-join $charArray
}
First, we turn the string into an array of chars.
Then, we pass the char array into the static method Reverse of the class Array from .NET.
Finally, we use -join to concatenate this char array back into one single string.
Array.Reverse method.
join range operator
Using range operator and -join
function ReverseString([string] $String) {
-join $String[$String.Length..0]
}
Using range from $String.Length..0, we created a range of indices from the length down to 0.
Apply the range to the string give us an array of object, in this case an array of char in reverse order of the original string.
Then we use -join to concatenate these character back into a single string, effectively reversing the input string.
Note : Technically speaking the valid range is from ($String.Length-1)..0 due to the nature of 0 based index.
However PowerShell is forgiving in these cases, and this convient feature allows simplified code, making it more concise and readable.
Whenever you need precise range of indices, make sure to use the correct range.
Range operator.
Join operator.
string builder
Using StringBuilder class
function ReverseString([string] $String) {
$strBuilder = [System.Text.StringBuilder]::new()
foreach ($i in ($String.Length - 1)..0) {
[void] $strBuilder.Append($String[$i])
}
$strBuilder.ToString()
}
First we create a new StringBuilder object from .NET.
Then we loop from the last index of the string to 0, each pass we append the current char to the StringBuilder object.
The append method has it own output showing some metadata, to avoid this we can ether cast [void] before the expression or pipe the output into Out-Null to suppress it.
When the loop is finished, we called the ToString() method on the StringBuilder object.
StringBuilder class.
Out-Null cmdlet.
ToString method.
Source: Exercism powershell/reverse-string