5

I have a line a text and I want the first word to be a variable, the second to be a second but all the rest to be consider one single var.

For example splitting Mary had a little lamb would result in:

  • $var[1] = Mary
  • $var[2] = had
  • $var[4] = a little lamb

How can I achieve this when I split by space?

henrycarteruk
  • 12,708
  • 2
  • 36
  • 40
Alexandru Lazar
  • 181
  • 1
  • 2
  • 8

3 Answers3

5

If you know the exact length of the first two words you can use .substring. Otherwise, you can use -Split and then use -join after assigning the first two array entries to your variables.

$mySplit = "alpha bravo charlie delta" -split " "
$var1 = $mySplit[0]
$var2 = $mySplit[1]
$var3 = $mySplit[2..($mySplit.length+2)] -join " "

The above example for $var3 grabs the array created by the -split and gets every entry except the first 2. The -join will then join the array entries back together into a single string separating each entry by a space.

henrycarteruk
  • 12,708
  • 2
  • 36
  • 40
Jason Snell
  • 1,425
  • 12
  • 22
4
$a="Mary had a little lamb"
$v1,$v2,$v3=$a.split(" ",3)

The split is what turns a string into an array, the "3" is the limit of how many parts to split into, and the variable list to the left of "=" is what make the result to end up in corresponding variables.

PS > $v3
a little lamb 
PS >
Vesper
  • 18,599
  • 6
  • 39
  • 61
1

Simply tell Split the number of elements to return:

$string = "Mary had a little lamb"
$var = $string.Split(" ",3)

Which will return:

Mary
had
a little lamb

You can then reference each element individually:

$var[0]
$var[1]
$var[2]
henrycarteruk
  • 12,708
  • 2
  • 36
  • 40