DarkAjax
DarkAjax

Reputation: 16223

How to turn a string into an array?

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

Answers (3)

user2555451
user2555451

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

Ansgar Wiechers
Ansgar Wiechers

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

Fridden
Fridden

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

Related Questions