从Scala中的String数组中删除第n个元素

nfc*_*-uk 7 scala

假设我有一个(我假设默认是可变的)Array [String]

如何在Scala中简单地删除第n个元素?

似乎没有简单的方法可用.

想要的东西(我做了这个):

def dropEle(n: Int): Array[T]
Selects all elements except the nth one.

n
the subscript of the element to drop from this Array.
Returns an Array consisting of all elements of this Array except the 
nth element, or else the complete Array, if this Array has less than 
n elements.
Run Code Online (Sandbox Code Playgroud)

非常感谢.

som*_*ytt 8

这就是观点的意义所在.

scala> implicit class Foo[T](as: Array[T]) {
     | def dropping(i: Int) = as.view.take(i) ++ as.view.drop(i+1)
     | }
defined class Foo

scala> (1 to 10 toArray) dropping 3
warning: there were 1 feature warning(s); re-run with -feature for details
res9: scala.collection.SeqView[Int,Array[Int]] = SeqViewSA(...)

scala> .toList
res10: List[Int] = List(1, 2, 3, 5, 6, 7, 8, 9, 10)
Run Code Online (Sandbox Code Playgroud)


Xav*_*hot 6

大多数集合都有一个patch可以“滥用”的方法来删除特定索引处的元素:

Array('a', 'b', 'c', 'd', 'e', 'f', 'g').patch(3, Nil, 1)
// Array('a', 'b', 'c', 'e', 'f', 'g')
Run Code Online (Sandbox Code Playgroud)

这:

  • 删除1索引处的元素3

  • 在索引处插入Nil(空序列)3

换句话说,这意味着“用空序列修补索引 3 处的 1 个元素”。


请注意,此处n是要在集合中删除的项目的从 0 开始的索引。


swa*_*ock 5

问题在于您选择的半可变集合,因为Array的元素可能会发生变异但其大小无法更改.你真的想要一个已经提供"删除(索引)"方法的Buffer.

假设您已经有一个Array,您可以轻松地将它转换为Buffer或从Buffer转换它以执行此操作

def remove(a: Array[String], i: index): Array[String] = {
  val b = a.toBuffer
  b.remove(i)
  b.toArray
} 
Run Code Online (Sandbox Code Playgroud)


Rad*_*sky 3

def dropEle[T](n: Int, in: Array[T]): Array[T] = in.take(n - 1) ++ in.drop(n)
Run Code Online (Sandbox Code Playgroud)