How to split a string into words in Kotlin

2 Answers

0 votes
fun splitString(s: String, delims: String): List<String> {
    val re: Regex = Regex(delims)
    val parts: List<String> = re.split(s)

    return parts.filter { it.isNotEmpty() }
}

fun main() {
    val s: String = "-c, c++.. c#:: -java ,php...python      kotlin"
    val delims: String = "[ ,.:\\-!]+"

    val tokens: List<String> = splitString(s, delims)

    for (t in tokens) {
        println(t)
    }
}


/*
run:

c
c++
c#
java
php
python
kotlin

*/

 



answered Aug 29 by avibootz
0 votes
fun splitString(s: String, delims: String): List<String> {
    val delimSet: Set<Char> = delims.toSet()

    val normalized: String = buildString {
        for (ch in s) {
            append(if (ch in delimSet) ' ' else ch)
        }
    }

    return normalized.split(" ").filter { it.isNotEmpty() }
}

fun main() {
    val s: String = "-c, c++.. c#:: -java ,php...python      go!"
    val delims: String = " ,.:\\-!"

    val tokens: List<String> = splitString(s, delims)

    for (t in tokens) {
        println(t)
    }
}


/*
run:

c
c++
c#
java
php
python
go

*/

 



answered Aug 29 by avibootz
...