Sort String Alphabetically

Hello everybody,

Doing some exercises here and this one I need help, I tried to search in previous topics and online but could not find anything concrete.

I basically need to take the string “PowerShell Forever” and display the characters in alphabetic order.
like “eeefh…”

The hint in the exercise says: “A string is an array of characters that you can join together any way you want.”

So far I got this:

$a = "PowerShell Forever"
$achar = $a.ToCharArray()
$achar | Sort-Object

This does not work and it only puts the same characters together.

I won’t be looking at the exercise solution and I am not looking for an actual answer here but more like a guidance what I can really do to continue on this one.

Looking at the documentation about_Join I can’t seem to understand what it is that I need to join to make this happen.

Thanks,
Lucas Fontes.

-join is a string operator which takes a value of what you want to go in between the joined values. If you want nothing between them then -join ‘’ (two single quotes)

1 Like

What exactly do you mean? It works exactly like it is supposed to work. :man_shrugging:t3:
The output looks like this:

 
F
P
S
e
e
e
e
h
l
l
o
o
r
r
r
v
w

If you like to (re-)join this to a string you can do it like this:

($achar | Sort-Object ) -join ''

Hi Olaf,

That output from Sort-Object is not sorting them alphabetically, the letter “e” should be at the beginning, followed by “f” and so on, this is what I meant.

The sort works but not alphabetically.

Ok, Now I understood how the Sort-Object works for strings, it takes the Upper case characters and puts them on top of the sorting, I was confused and like, why the F,P,S were at the beginning ? lol

I came up with this and now it worked great:


$a = "PowerShell Forever"
$achar = $a.ToLower().ToCharArray()
($achar | Sort-Object ) -join ''

Output:

eeeefhllooprrrsvw

Thanks for the replies @Olaf and @neemobeer

You may think of the ASCII table and the numbers associated to the according characters as the base for the sorting.

1 Like

Not bad, but I wouldn’t award full marks for that :mortar_board:

Hint: try splitting if you want to preserve the case.

OK Matt … you peaked my curiosity. Are you saying that using Split, one can obtain this as the result?

eeeeFhllooPrrrSvw

Care to elaborate? Thanks Matt.

Hi Tony,

Like this:

('PowerShell Forever' -split '' | Sort-Object) -join ''
1 Like

Thanks for the solution Matt :slight_smile: I think I tried every combination but that one :frowning:

1 Like