2

How do I create an array of integers from a variable containing the string "3 4 5 4 3"?

1
  • What have you tried, and in what way(s) has it not worked? Please don't just ask for an answer with no demonstration of attempting it yourself. Commented Dec 9, 2012 at 13:22

2 Answers 2

8

I prefer:

[int[]] -split "3 4 5  4   3"

-split handles whitespace space better than String.Split(). With String.Split(), if there is more than one space between numbers you wind up with empty strings in the generated array. The empty strings are coerced to 0 by PowerShell e.g.:

C:\PS> [int[]]"3 4 5  4   3".Split()
3
4
5
0
4
0
0
3
Sign up to request clarification or add additional context in comments.

Comments

5

Splitting the string creates an array of string, add a cast to an array of integers:

[int[]]"3 4 5 4 3".Split()

Comments

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.