Kotlin Split String Ignore Empty

April 8, 2019

If you use split, it will return results with empty string if

"".split(",")       // [""]
"hello,".split(",") // ["hello", ""]

Kotlin extension to split string and filter out empty string.

fun CharSequence.splitIgnoreEmpty(vararg delimiters: String): List<String> {
    return this.split(*delimiters).filter {
        it.isNotEmpty()
    }
}
"".splitIgnoreEmpty(",")            // []
"hello".splitIgnoreEmpty(",")       // ["hello"]
"hello,".splitIgnoreEmpty(",")      // ["hello"]
"hello,world".splitIgnoreEmpty(",") // ["hello", "world"]
This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.