Split a string on newline in Kotlin
This article explores different ways to split a string on newline in Kotlin.
Different operating systems uses different line terminator wrt each other. For example, Windows uses a carriage-return and line-feed character (\r\n) as a line terminator. Mac uses a carriage-return character (represented as \r) and Unix uses a line-feed character (represented as \n) to mark the end of a line.
The split() function is often used to split a string around matches of a regular expression. To split a string on newlines, we can use the regular expression \r?\n|\r which matches with all different line terminator i.e., \r\n, \r, and \n.
|
1 2 3 4 5 6 7 |
fun main() { val str = "A\nB\nC" val lines = str.split("\r?\n|\r".toRegex()).toTypedArray() println(listOf(*lines)) // [A, B, C] } |
To skip empty lines, we can change the regular expression to [\r\n]+.
|
1 2 3 4 5 6 7 |
fun main() { val str = "A\nB\n\n\r\nC" val lines = str.split("[\r\n]+".toRegex()).toTypedArray() println(listOf(*lines)) // [A, B, C] } |
To match with any Unicode linebreak sequence, we can use the linebreak matcher \R.
|
1 2 3 4 5 6 7 |
fun main() { val str = "A\r\nB\r\nC" val lines = str.split("\\R".toRegex()).toTypedArray() println(listOf(*lines)) // [A, B, C] } |
That’s all about splitting a string on newline 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 :)