说我有一个字符串
"Hello! How do you do? Good day!"
我希望将其拆分,我的分隔符为:?
和!
使用“拆分”功能,结果将是:
`[Hello, How do you do, Good day]`
但是,我希望它是:
`[Hello, !, How do you do, ?, Good day, !]`
答案 0 :(得分:9)
以下是Java中的类似问题:How to split a string, but also keep the delimiters?
使用前瞻。在Kotlin中,代码可能是这样的:
fun main(args: Array<String>) {
val str = "Hello! How do you do? Good day!"
val reg = Regex("(?<=[!?])|(?=[!?])")
var list = str.split(reg)
println(list)
}
这个输出是:
[Hello, !, How do you do, ?, Good day, !]
答案 1 :(得分:1)
这是我的这种功能版本:
fun String.splitKeeping(str: String): List<String> {
return this.split(str).flatMap {listOf(it, str)}.dropLast(1).filterNot {it.isEmpty()}
}
fun String.splitKeeping(vararg strs: String): List<String> {
var res = listOf(this)
strs.forEach {str ->
res = res.flatMap {it.splitKeeping(str)}
}
return res
}
//USAGE:
"Hello! How do you do? Good day!".splitKeeping("!", "?")
它不是很快(方形复杂度),但适用于相对较短的字符串。
答案 2 :(得分:0)
这是一个扩展函数,其中包装了讨论过的代码here:
private const val withDelimiter = "((?<=%1\$s)|(?=%1\$s))"
fun Regex.splitWithDelimiter(input: CharSequence) =
Regex(withDelimiter.format(this.pattern)).split(input)