有没有Scala库API方法(如果没有,有没有惯用的方法)可以获取较大字符串(源)中子字符串(目标)的所有索引列表?我尝试查看了ScalaDoc,但没有找到任何明显的东西。有很多方法做很多有用的事情,我猜我只是没有提交正确的搜索词。
例如,如果我有一个源字符串“name:Yo,name:Jim,name:name,name:bozo”,并使用一个目标字符串“name:”,那么我想得到一个List[Int],其中包含List(0, 8, 17, 27)。
这是我的快速解决问题的方法:
例如,如果我有一个源字符串“name:Yo,name:Jim,name:name,name:bozo”,并使用一个目标字符串“name:”,那么我想得到一个List[Int],其中包含List(0, 8, 17, 27)。
这是我的快速解决问题的方法:
def indexesOf(source: String, target: String, index: Int = 0, withinOverlaps: Boolean = false): List[Int] = {
def recursive(index: Int, accumulator: List[Int]): List[Int] = {
if (!(index < source.size)) accumulator
else {
val position = source.indexOf(target, index)
if (position == -1) accumulator
else {
recursive(position + (if (withinOverlaps) 1 else target.size), position :: accumulator)
}
}
}
if (target.size <= source.size) {
if (!source.equals(target)) {
recursive(0, Nil).reverse
}
else List(0)
}
else Nil
}
如果您能指导我用适当的标准库入口替换它,将不胜感激。
更新于2019年6月16日:
进一步压缩代码:
def indexesOf(source: String, target: String, index: Int = 0, withinOverlaps: Boolean = false): List[Int] = {
def recursive(indexTarget: Int = index, accumulator: List[Int] = Nil): List[Int] = {
val position = source.indexOf(target, indexTarget)
if (position == -1)
accumulator
else
recursive(position + (if (withinOverlaps) 1 else target.size), position :: accumulator)
}
recursive().reverse
}
更新时间:2014年7月22日:
受Siddhartha Dutta答案的启发,我进一步优化了我的代码。现在它看起来像这样:
def indexesOf(source: String, target: String, index: Int = 0, withinOverlaps: Boolean = false): List[Int] = {
@tailrec def recursive(indexTarget: Int, accumulator: List[Int]): List[Int] = {
val position = source.indexOf(target, indexTarget)
if (position == -1) accumulator
else
recursive(position + (if (withinOverlaps) 1 else target.size), position :: accumulator)
}
recursive(index, Nil).reverse
}
此外,如果我有一个源字符串 "aaaaaaaa",并使用目标字符串 "aa",我希望默认情况下返回一个List[Int],其中包含跳过在已找到的子字符串内开始搜索的位置 List(0, 2, 4, 6)。可以通过将 withinOverlaps 参数设置为 "true" 来覆盖默认情况,在 "aaaaaaaa"/"aa" 的情况下,它会返回 List(0, 1, 2, 3, 4, 5, 6)。