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?
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
Casting the string to a character array is probably the simplest way to go about this:
PS C:\>
PS C:\>
abc
PS C:\>
a
b
c
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.