Powershell

Reverse a string in powershell

Exactly a month in of working from home and social distancing, last night I was playing around with some scripts and at some point I needed to read the last index or an array without knowing its length. Easy enough, regardless the array length, the last index is always -1:

PS C:\> @(1,2,3,4,5,6,7,8)[-1]
8

This reminded me of a conversation I had some time ago with a colleague, he was trying to convince me of much much Python is better than Powershell (and I stoically resisted and counter-punched πŸ˜‰). One of the many arguments he used to convince me was to show how easy it is in Python to revert a string:

>>> "Hello World"[::-1]
'dlroW olleH'

True, that looks easy and elegant but the Powershell solution is not that bad, is it?

PS C:\ > "Hello World"[-1..-20] -join ''
dlroW olleH

A string is an array of characters, so I’m using the square brackets to read a sequence of characters from the original string. The trick here is that my starting point is index -1 (the last character of the string) and I’m moving backwards towards the first character; here I’m just using a negative index greater than the string length and powershell happily complies. I also need to join the output (with an empty string). If you want to be exact with the string length you could use something like:

PS C:\> $string = 'Hello World'
PS C:\> $string[-1..-$string.Length] -join ''
dlroW olleH

To follow by faith alone is to follow blindly – Benjamin Franklin

One Comment

  • Harjit S. Batra

    How about this as an example of reversing one or many strings without first storing them in variables!

    ‘Skyline Pigeon’, ‘Honky Cat’|% {-join($_[-1..-$_.Length])}

Leave a Reply

Your email address will not be published. Required fields are marked *

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