Removing the nth element from a String array in Scala

Assuming I have (what I assume is changed by default) Array [String]

How can one simply remove the nth element in Scala?

There is no simple method.

Want something like (I did it):

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.

Many thanks.

+7
source share
5 answers

This is what submission is for.

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)
+8
source

The problem is that you have chosen a semi-mutable collection of your choice, as the array elements can be mutated, but their size cannot be resized. You really need a buffer that the "remove (index)" method already provides.

, , , .

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

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

+3

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
}
0

:A](from:Int,other:scala.collection.IterableOnce[B],replaced:Int):CC[B] rel="nofollow noreferrer"> patch :

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

:

  • 1 3

  • Nil ( ) 3

" 1 3 ".


Note that here nis an index based on the 0 element that needs to be removed in the collection.

0
source

All Articles