在Scala中从字符串数组中删除第n个元素

mzaanser  于 8个月前  发布在  Scala
关注(0)|答案(6)|浏览(81)

假设我有一个(默认情况下我假设是可变的)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.

非常感谢。

hgb9j2n6

hgb9j2n61#

这就是观点的作用。

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)
rta7y2nd

rta7y2nd2#

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

Array('a', 'b', 'c', 'd', 'e', 'f', 'g').patch(3, Nil, 1)
// Array('a', 'b', 'c', 'e', 'f', 'g')

这是:

  • 删除索引3处的1元素
  • 在索引3处插入Nil(空序列)

换句话说,这意味着“用空序列修补索引3处的1个元素”。
请注意,在这里,n是集合中要删除的项的从0开始的索引。

ddhy6vgd

ddhy6vgd3#

问题在于您选择的半可变集合,因为Array的元素可能会发生变化,但其大小无法更改。你真的需要一个已经提供了“remove(index)”方法的Buffer。
假设您已经有了一个Array,您可以轻松地将其转换为Buffer或从Buffer转换为Array,以便执行此操作

def remove(a: Array[String], i: index): Array[String] = {
  val b = a.toBuffer
  b.remove(i)
  b.toArray
}
wydwbb8l

wydwbb8l4#

def dropEle[T](n: Int, in: Array[T]): Array[T] = in.take(n - 1) ++ in.drop(n)
sbdsn5lh

sbdsn5lh5#

对于引用数组中第一个元素的nth=0

def dropEle[T](nth: Int, in: Array[T]): Array[T] = {
  in.view.zipWithIndex.filter{ e => e._2 != nth }.map{ kv => kv._1 }.toArray
}

一个稍微紧凑的语法包括

def dropEle[T](nth: Int, in: Array[T]): Array[T] = {
  in.view.zipWithIndex.filter{ _._2 != nth }.map{ _._1 }.toArray
}
sf6xfgos

sf6xfgos6#

s是字符串数组,index是要从s中删除的数组元素的索引

def remove(s: Array[String], index: Int): Array[String] = {
    Array.concat(s.slice(0, index), s.slice(index+1, s.size))
}

相关问题