Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create an array from a string in PowerShell

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

like image 629
János Schneider Avatar asked Jan 27 '26 03:01

János Schneider


2 Answers

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
like image 197
Keith Hill Avatar answered Jan 28 '26 19:01

Keith Hill


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

[int[]]"3 4 5 4 3".Split()
like image 41
Shay Levy Avatar answered Jan 28 '26 18:01

Shay Levy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!