kotlin - 在 Kotlin-way 中获取字符串中包含的子字符串的索引
问题描述
我想实现一个函数,它将返回指定字符串中子字符串的索引。现在我是用 Java 风格做的:
public fun String?.indexesOf(substr: String, ignoreCase: Boolean = true): List<Int> {
var list = mutableListOf<Int>()
if (substr.isNullOrBlank()) return list
var count = 0;
this?.split(substr, ignoreCase = ignoreCase)?.forEach {
count += it.length
list.add(count)
count += substr.length
}
list.remove(list.get(list.size-1))
return list
}
但我不认为这是一个 kotlin 方式的解决方案。它看起来最像典型的 java 程序,但用 kotlin 编写。如何使用 kotlin 更优雅地实现这一点?
解决方案
我会做什么如下:
fun ignoreCaseOpt(ignoreCase: Boolean) =
if (ignoreCase) setOf(RegexOption.IGNORE_CASE) else emptySet()
fun String?.indexesOf(pat: String, ignoreCase: Boolean = true): List<Int> =
pat.toRegex(ignoreCaseOpt(ignoreCase))
.findAll(this?: "")
.map { it.range.first }
.toList()
// check:
println("xabcaBd".indexesOf("ab", true))
println("xabcaBd".indexesOf("ab", false))
println("xabcaBd".indexesOf("abx", true))
val s: String? = null
println(s.indexesOf("aaa"))
// output:
[1, 4]
[1]
[]
[]
推荐阅读
- reactjs - 错误:缩小反应错误 #130
- google-analytics - Google Analytics(分析)数据保留政策 - 批量更改?
- python - 在 MacOS 上安装 Kivy 的问题
- python - 过滤列表的索引
- javascript - 使用文本淡入 div
- c++ - 在 C++ 中使用 GDI+ 平滑动画
- javascript - 在Javascript中动态生成带有图标名称的字体真棒
- node.js - 在 Node 项目中使用 NPM 处理 CSS 文件
- dart - 如何使图像上的坐标在颤动中相对于设备屏幕动态和响应?
- vim - 在 .vimrc 的开头添加 has('vim_starting')