6

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. The input the user is prompted to enter fruit with a space between (I will use Read-Host for that). So then I need to convert a space-separated string to an array for the foreach loop.

Thank you...

1
  • 2
    You can use split like: $Text -split ' ' Commented Jun 6, 2017 at 17:25

4 Answers 4

11

I would use the -split regex operator, like so:

$text = -split $text

You can also use it directly in the foreach() loop declaration:

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).

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

1 Comment

Oh this is nice.. Thank you!
2

Use Split()

$text = $text.Split(" ")

Comments

1
$text = $text -split " "

will work, provided that none of your fruit names are two words that you want to keep together.

1 Comment

Lets just only one word fruits will be used for this exercise.
0

$Text.Split(' ')

need more characters for answer.

3 Comments

Say something useful or educative about $Text.Split(' ') rather than "need more characters for answer" - there's a reason more characters are required.
Thanks for the quick replies... But how do I add the splited words to an array with double quotes etc... Is there a way to do this via read-host... i.e. what the user enters goes into an array? rather than words and spaces?
Ok I see now... I can use $Text.Split in the foreach loop.... i.e. foreach ($F in Text.Split(' '))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.