How to Split String in Kotlin: Syntax and Examples
In Kotlin, you can split a string using the
split() function by passing a delimiter like a character or string. This function returns a list of substrings separated by the delimiter.Syntax
The basic syntax to split a string in Kotlin is using the split() function. You provide one or more delimiters as arguments, and it returns a list of substrings.
- delimiter(s): The character(s) or string(s) where the split happens.
- limit (optional): Maximum number of splits to perform.
kotlin
val parts = originalString.split(delimiter)Example
This example shows how to split a sentence into words using space as the delimiter.
kotlin
fun main() {
val sentence = "Kotlin is fun to learn"
val words = sentence.split(" ")
println(words)
}Output
[Kotlin, is, fun, to, learn]
Common Pitfalls
One common mistake is forgetting that split() returns a list, not an array or string. Also, if the delimiter is not found, the whole string is returned as a single element list. Using multiple delimiters requires passing them as varargs or a regex.
kotlin
fun main() {
val text = "apple,banana;cherry"
// Wrong: splitting by a single string won't split by both ',' and ';'
val wrongSplit = text.split(",;")
println(wrongSplit) // Output: [apple,banana;cherry]
// Right: split by multiple delimiters using regex
val rightSplit = text.split(",", ";")
println(rightSplit) // Output: [apple, banana, cherry]
}Output
[apple,banana;cherry]
[apple, banana, cherry]
Key Takeaways
Use
split() with a delimiter to divide a string into parts.split() returns a list of substrings, not a single string.To split by multiple delimiters, pass them as separate arguments or use a regex.
If the delimiter is missing, the result is a list with the original string as one element.