cha*_*ium 6 string scala indexof
是否有Scala库API方法(如果不是,惯用方法)获取更大字符串(源)中子字符串(目标)的所有索引的列表?我试图浏览ScalaDoc,但无法找到任何明显的东西.有很多方法可以做很多有用的事情,我猜我只是没有提交正确的搜索条件.
例如,如果我有一个源名称为"name:Yo,name:Jim,name:name,name:bozo",我使用的是"name:"的目标字符串,我想找回一个List [Int]列表(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
}
Run Code Online (Sandbox Code Playgroud)
任何指导,你可以给我用适当的标准库入口点替换它将非常感谢.
更新2014/Jul/22:
受Siddhartha Dutta的回答启发,我加强了我的代码.它现在看起来像这样:
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
}
Run Code Online (Sandbox Code Playgroud)
另外,如果我有一个源代码字符串"aaaaaaaa"并使用目标字符串"aa",我希望默认情况下返回List(0,2,4,6)的List [Int],它会跳过一个从找到的子字符串开始搜索.可以通过为"aaaaaaa"/"aa"情况下返回List(0,1,2,3,4,5,6)的withinOverlaps参数传递"true"来覆盖默认值.
我总是倾向于进入像这样的问题的正则表达技巧.我不会说这是正确的,但这是一个很少的代码.:)
val r = "\\Qname\\E".r
val ex = "name:Yo,name:Jim,name:name,name:bozo"
val is = r.findAllMatchIn(ex).map(_.start).toList
Run Code Online (Sandbox Code Playgroud)
引号\\Q和\\E不必需的这种情况下,但如果你正在寻找的字符串包含任何特殊字符,那么这将是.
| 归档时间: |
|
| 查看次数: |
1128 次 |
| 最近记录: |