String.split() / joinToString()
Functions for splitting a string by a delimiter, or joining the elements of a collection into a string with a separator.
Syntax
// Splits a string by the given delimiter and returns a list. string.split(delimiter, limit = maxSplits) // Joins the elements of a collection with a separator and returns a string. collection.joinToString(separator = separator, prefix = prefix, postfix = postfix)
Method List
| Method | Description |
|---|---|
| split(vararg delimiters: String) | Splits the string by the specified string delimiters and returns a List<String>. |
| split(vararg delimiters: Char) | Splits the string by the specified characters and returns a List<String>. |
| joinToString(separator, prefix, postfix, limit, truncated, transform) | Joins the elements of a collection into a string. All parameters are optional. |
| joinTo(buffer, separator, ...) | Appends the joined result to an existing Appendable. |
Sample Code
fun main() {
// Split by comma.
val csv = "apple,orange,grape,peach"
val fruits = csv.split(",")
println(fruits) // [apple, orange, grape, peach]
// Limit the number of splits.
val limited = csv.split(",", limit = 2)
println(limited) // [apple, orange,grape,peach]
// Split by multiple delimiters.
val text = "one two,three;four"
val words = text.split(" ", ",", ";")
println(words) // [one, two, three, four]
// Join a list into a string.
val list = listOf("Kotlin", "Java", "Swift")
val joined = list.joinToString(separator = " / ")
println(joined) // Kotlin / Java / Swift
// Add a prefix and postfix.
val withBrackets = list.joinToString(separator = ", ", prefix = "[", postfix = "]")
println(withBrackets) // [Kotlin, Java, Swift]
// Join with a transformation applied to each element.
val numbers = listOf(1, 2, 3, 4, 5)
val result = numbers.joinToString(separator = " + ", transform = { it.toString() })
println(result) // 1 + 2 + 3 + 4 + 5
}
Notes
split() splits a string by a delimiter and returns a List<String>. To use a regular expression, pass a Regex object as the argument. If delimiters appear consecutively, empty strings will be included in the result list. To exclude them, use filter { it.isNotEmpty() }.
joinToString() joins the elements of a collection into a single string. All parameters have default values, so calling it without arguments joins elements with a comma separator. Use limit to cap the number of elements included; any excess is replaced with the value of truncated (default: "...").
If you find any errors or copyright issues, please contact us.