简体   繁体   English

如何将字符串转换为数组?

[英]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") ??? 我想知道,如何将其转换为数组:( ("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... 但这给了我一个数组:( ("","a","b","c","") ,在其他数组之前和之后都有一个空元素...

I can circumvent this doing $x -split "" -ne "" , but that seems kind of weird. 我可以通过$x -split "" -ne ""来避免这种情况,但这似乎很奇怪。 Is there a better way? 有没有更好的办法?

You can use the System.String.ToCharArray method: 您可以使用System.String.ToCharArray方法:

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:\> $x = 'abc'
PS C:\> $x
abc
PS C:\> [char[]]$x
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 希望这可以帮助/ Fridden

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM