Split String by delimiter in Kotlin Split String by delimiter in Kotlin

Page content

In this post, we’ll see quick examples of splitting a string by delimiter to list in Kotlin.

split() to list

Split a string by colon (:) delimiter and print the list

val str = "A:B:C"
val delim = ":"

val list = str.split(delim)

println(list) // [A, B, C]

split() and trim()

Split urls separated by comma (,) delimiter, trim the spaces, and print the list

val brokerUrls = "http://broker1.com , http://broker2.com , http://broker3.com"
val delim = ","

val list = brokerUrls.split(delim).map { it.trim() }

println(list) // [http://broker1.com, http://broker2.com, http://broker3.com]

split() by multiple delimiters

Split pairs by semicolon (;) and equal (=) delimiters, and print the extracted list of keys and values

val pairs = "key1=value1;key2=value2;key3=value3"

val list = pairs.split(";", "=").map { it.trim() }

println(list) // [key1, value1, key2, value2, key3, value3]

split() to array

Split a pair by equal (=) delimiter and print the array elements by index

val pair = "key=value"
val delim = "="

val array = pair.split(delim).toTypedArray()

println(array[0]) // key
println(array[1]) // value

removeSurrounding(), split(), and trim()

Given the json as a string, first remove the prefix and suffix from the string using removeSurrounding(), then split the string by multiple delimiters, and finally trim the spaces before returning the list

val str = "{ key1: value1, key2: value2, key3: value3 }"

val list = str.removeSurrounding("{", "}").split(":", ",").map { it.trim() }

println(list) // [key1, value1, key2, value2, key3, value3]

split string to equal parts by n letters

We use chunked() function to split the string into equal parts, each part contains 3 letters of currency code

val str = "USDAUDINRSGDEUR"

val list = str.chunked(3)

println(list) // [USD, AUD, INR, SGD, EUR]

split string by new line

We use lines() function to split the string into a list of lines delimited by any of the following character sequences: CRLF, LF or CR.

val str = "codingnconcepts.com\nKotlin Tutorial\rSplit String"

val list = str.lines()

println(list) // [codingnconcepts.com, Kotlin Tutorial, Split String]