Reputation: 16223
Assuming I have a string like this:
$x = "abc"
I want to know, How can I turn it into an array like: ("a","b","c")
???
Currently I use something like:
$x -split ""
But that gives me an array like: ("","a","b","c","")
with an empty element before and after the other ones...
I can circumvent this doing $x -split "" -ne ""
, but that seems kind of weird. Is there a better way?
Upvotes: 1
Views: 256
Reputation:
You can use the System.String.ToCharArray
method:
PS > $x = "abc"
PS > $x.ToCharArray()
a
b
c
PS > ($x.ToCharArray()).GetType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Char[] System.Array
Upvotes: 4
Reputation: 200203
Casting the string to a character array is probably the simplest way to go about this:
PS C:\> $x = 'abc'
PS C:\> $x
abc
PS C:\> [char[]]$x
a
b
c
Upvotes: 2
Reputation: 189
You could also use a regular expression to filter out the beginning and end of the string:
PS > $x -split "(?<!(^|$))"
A
B
C
PS >
Hope this helps /Fridden
Upvotes: 1