[英]Powershell convert string to array
How do I change: 我该如何改变:
$Text = "Apple Pear Peach Banana"
to 至
$Text = @("Apple", "Pear", "Peach", "Banana")
I am planning to feed the array to a foreach
loop. 我计划将数组提供给foreach
循环。 The input the user is prompted to enter fruit with a space between (I will use Read-Host
for that). 提示用户输入水果,其间有空格(我将使用Read-Host
)。 So then I need to convert a space-separated string to an array for the foreach
loop. 那么我需要将空格分隔的字符串转换为foreach
循环的数组。
Thank you... 谢谢...
I would use the -split
regex operator , like so: 我会使用-split
regex运算符 ,如下所示:
$text = -split $text
You can also use it directly in the foreach()
loop declaration: 您也可以直接在foreach()
循环声明中使用它:
foreach($fruit in -split $text)
{
"$fruit is a fruit"
}
In unary mode (like above), -split
defaults to splitting on the delimeter \\s+
(1 or more whitespace characters). 在一元模式下(如上所述),- -split
默认在分隔符上分割\\s+
(1个或多个空格字符)。
This is nice if a user accidentally enters consecutive spaces: 如果用户意外进入连续的空格,这很好:
PS C:\> $text = Read-Host 'Input fruit names'
Input fruit names: Apple Pear Peaches Banana
PS C:\> $text = -split $text
PS C:\> $text
Apple
Pear
Peaches
Banana
使用Split()
$text = $text.Split(" ")
$Text.Split(' ') $ Text.Split('')
need more characters for answer. 需要更多的字符来回答。
$text = $text -split " "
如果你的水果名字都不是你想要保持在一起的两个单词,那就行了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.