1

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?

3 Answers 3

4

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    
Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.