我有一个程序,我试图找到字母“e”第 n 次出现的索引。我猜到了这样的事情......
def findE(line: String, ignore: Int) : Int = {
val pattern = "e".r
val index = line.indexOf(pattern(ignore+1))
index
}
哪里
ignore+1
是所需的组,但语法无效。想知道是否有人知道如何解决这个问题?
如果我是你,我会使用标准组合器。
> "abcdeabcdeabcde".zipWithIndex.collect {
case ('e', index) => index
}
res1: collection.immutable.IndexedSeq[Int] = Vector(4, 9, 14)
只要采取索引 5 处的任何内容(如果存在),这就是您的答案。
这是我尝试低成本抽象的实现。
/** laizly finds all indicies of a given char */
def indexesOf(s:String, of:Char): Iterator[Int] =
def from(idx:Int) = s.indexOf(of, idx+1)
Iterator.iterate(from(0))(from).takeWhile(_ >= 0)
def dropLines(s:String, x:Int) = x match
case 0 => s
case other =>
indexesOf(s, '\n').drop(x-1).headOption match
case Some(x) => s.drop(x+1)
case None => ""