Split a string using a delimiter in Kotlin
This article explores different ways to split a string into an array using a given delimiter in Kotlin.
1. Using String’s split() function
The standard solution to split a string in Kotlin is with the native split() function, which takes one or more delimiters as an argument and splits the string around occurrences of the specified delimiters.
|
1 2 3 4 5 6 7 8 |
fun main() { val str = "A:B:C" val delim = ":" val list = str.split(delim) println(list) // [A, B, C] } |
The split() function returns a list of strings. If you want to convert the list into an array, call the toTypedArray() function.
|
1 2 3 4 5 6 7 |
fun main() { val str = "A:B:C" val delim = ":" val arr = str.split(delim).toTypedArray() println(arr.contentToString()) // [A, B, C] } |
2. Using Pattern’s split() function
You can also use Pattern’s split() function, which returns an array of strings computed by splitting the input around matches of the given pattern.
|
1 2 3 4 5 6 7 8 9 10 |
import java.util.regex.Pattern fun main() { val str = "A:B:C" val delim = ":" val arr = Pattern.compile(delim).split(str) println(arr.contentToString()) // [A, B, C] } |
If your delimiter happens to be the same as special characters in regex like a dot(.), pipe(|) or dollar($), you need to escape them first.
|
1 2 3 4 5 6 7 8 9 10 |
import java.util.regex.Pattern fun main() { val str = "A.B.C" val delim = "\\." val arr = Pattern.compile(delim).split(str) println(arr.contentToString()) // [A, B, C] } |
That’s all about splitting a string using a delimiter in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)