Scala 中第 n 个模式匹配的索引

问题描述 投票:0回答:2

我有一个程序,我试图找到字母“e”第 n 次出现的索引。我猜到了这样的事情......

def findE(line: String, ignore: Int) : Int = {
    val pattern = "e".r
    val index = line.indexOf(pattern(ignore+1))
    index
}

哪里

ignore+1 

是所需的组,但语法无效。想知道是否有人知道如何解决这个问题?

regex scala
2个回答
3
投票

如果我是你,我会使用标准组合器。

> "abcdeabcdeabcde".zipWithIndex.collect {
    case ('e', index) => index
  }
res1: collection.immutable.IndexedSeq[Int] = Vector(4, 9, 14)

只要采取索引 5 处的任何内容(如果存在),这就是您的答案。


0
投票

这是我尝试低成本抽象的实现。

/** 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 => ""
  • 它永远不会迭代整个字符串来查找所有行
  • 结果字符串是在一个 s.drop(chars) 中生成的,同时没有生成其他字符串
  • 为了找到分割点,我们有效地调用 s.indexOf('/n', prevIndex) n 次。
  • 仅使用很少的轻量级迭代器来管理流程
© www.soinside.com 2019 - 2024. All rights reserved.