假设我有一个(默认情况下我假设是可变的)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.
非常感谢。
6条答案
按热度按时间hgb9j2n61#
这就是观点的作用。
rta7y2nd2#
大多数集合都有一个
patch
方法,可以被“滥用”来删除特定索引处的元素:这是:
3
处的1
元素3
处插入Nil
(空序列)换句话说,这意味着“用空序列修补索引3处的1个元素”。
请注意,在这里,
n
是集合中要删除的项的从0开始的索引。ddhy6vgd3#
问题在于您选择的半可变集合,因为Array的元素可能会发生变化,但其大小无法更改。你真的需要一个已经提供了“remove(index)”方法的Buffer。
假设您已经有了一个Array,您可以轻松地将其转换为Buffer或从Buffer转换为Array,以便执行此操作
wydwbb8l4#
sbdsn5lh5#
对于引用数组中第一个元素的
nth=0
,一个稍微紧凑的语法包括
sf6xfgos6#
s
是字符串数组,index
是要从s
中删除的数组元素的索引