PowerShell

PowerShell: How to reverse a String

In this post, I will show how to reverse a string, i.e., how to change it from back to front. To spark some ideas on how to approach this, I’ve provided a few examples.
Enjoy exploring the possibilities!

# 1
$originalString = "Hello, World!"
$reversedString = -join $originalString[-1..-($originalString.Length)]
Write-Host $reversedString

# 2
$string = 'Patrick'
-join $string.ToCharArray()[-1..-$string.Length]

# 3
-join 'Patrick'.ToChararray()[-1..-'Patrick'.Length]

# 4
$namen = 'Patrick','Herbert','Hans','Peter'
foreach ($name in $namen) {
    -join $name.ToCharArray()[-1..-$name.Length]
}

# 5 # Out of Topic: Reverse Numbers
(1..100)[-1..-100] # oder 100..1
100..1

Hope this was helpful.

Categories: PowerShell

Tagged as: ,

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.