Powershell将字符串转换为数组

nix*_*eek 4 arrays string powershell foreach

我该如何改变:

$Text = "Apple Pear Peach Banana"
Run Code Online (Sandbox Code Playgroud)

$Text = @("Apple", "Pear", "Peach", "Banana")
Run Code Online (Sandbox Code Playgroud)

我计划将数组提供给foreach循环.提示用户输入水果,其间有空格(我将Read-Host用于此).那么我需要将空格分隔的字符串转换为foreach循环的数组.

谢谢...

Mat*_*sen 5

我会使用-split正则表达式运算符,如下所示:

$text = -split $text
Run Code Online (Sandbox Code Playgroud)

您也可以直接在foreach()循环声明中使用它:

foreach($fruit in -split $text)
{
    "$fruit is a fruit"
}
Run Code Online (Sandbox Code Playgroud)

在一元模式下(如上所述),-split 默认为在分隔符拆分\s+(1个或多个空格字符).

如果用户意外进入连续的空格,这很好:

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
Run Code Online (Sandbox Code Playgroud)


the*_*p3r 0

$Text.Split(' ')

需要更多字符来回答。