Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split a string and plant the delimiters between the splitted parts in Kotlin?

Tags:

split

kotlin

Say I have a string

"Hello! How do you do? Good day!"

and I want to split it, with my delimiters being: ? and ! using the "split" function the result would be:

`[Hello, How do you do, Good day]`

However, I want it to be:

`[Hello, !, How do you do, ?, Good day, !]`
like image 622
Dina Kleper Avatar asked May 10 '16 06:05

Dina Kleper


1 Answers

Here is a similar question in Java: How to split a string, but also keep the delimiters?

Use lookahead. In Kotlin, the code maybe like this:

fun main(args: Array<String>) {
    val str = "Hello! How do you do? Good day!"

    val reg = Regex("(?<=[!?])|(?=[!?])")

    var list = str.split(reg)

    println(list)
}

The output of this is:

[Hello, !, How do you do, ?, Good day, !]
like image 77
zhumengzhu Avatar answered Sep 30 '22 17:09

zhumengzhu