从Scala中的另一个数组中的元素替换一个数组中的元素

yar*_*ari 0 arrays loops functional-programming scala

我有两个数组。第一个数组的大小大于第二个数组的大小。

 var first  = (1 to 20).toArray
 var second = (1 to 5).toArray
Run Code Online (Sandbox Code Playgroud)

我想替换第一Ñ的元件第一阵列的元件的第二阵列。其中n是第二个数组的长度。使用For循环,我可以通过以下方式轻松地做到这一点

 var n = second.length
 for(i <- 0 until n)
 {
  first(i) = second(i)
 }
Run Code Online (Sandbox Code Playgroud)

我想问一下是否还有其他方法可以在Scala中以更实用的方式执行相同的操作?

Ped*_*uís 5

你可以这样做:

var first  = (1 to 20).toArray
var second = (1 to 5).toArray

val third = second ++ first.drop(second.length)
Run Code Online (Sandbox Code Playgroud)

结果:

third: Array[Int] = Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20)
Run Code Online (Sandbox Code Playgroud)