Kotlin Split String example

This Kotlin tutorial shows you ways to split string with Kotlin extension functions.

Overview

1. split() with Regex

This overload of split() method requires a value of Regex type, not String:

inline fun CharSequence.split(regex: Regex, limit: Int = 0): List<String>

Kotlin not only uses the same regular expression syntax and APIs as Java, but also has extension function toRegex() to convert a string into a regular expression.
So, our code could be:

Listt<String> = CharSequence.split("RegexSyntaxString".toRegex())

2. split() with delimiters

Instead of using Regex, you can specify character/string arguments as delimiters:

fun CharSequence.split(vararg delimiters: String, ignoreCase: Boolean = false, limit: Int = 0): List<String>

3. Split String by new line

To split string to lines, we use lines() function that splits the char sequence into a list of lines delimited by any of the following character sequences: CRLF, LF or CR.

fun CharSequence.lines(): List<String>

4. Split String into characters by length

We use chunked() function to split a String into List of characters by a given size (length).

fun CharSequence.chunked(size: Int): List<String>

Practice

1. split() with Regex

package com.bezkoder.splitstring

fun main(args: Array) {
  val str = "bezkoder.com = Programming Tutorials - Web Development - Mobile App"
	
  val separate1 = str.split("=|-".toRegex()).map { it.trim() }
  println(separate1)
}

Result:

[bezkoder.com, Programming Tutorials, Web Development, Mobile App]

2. split() with delimiters

package com.bezkoder.splitstring

fun main(args: Array) {
  val str = "bezkoder.com = Programming Tutorials - Web Development - Mobile App"

  val separate2 = str.split("=", "-").map { it.trim() }
  println(separate2)
}

Result:

[bezkoder.com, Programming Tutorials, Web Development, Mobile App]

3. Split String by new line

package com.bezkoder.splitstring

fun main(args: Array) {
  val str = "bezkoder.com\nProgramming Tutorials\rWeb Development"

  var separate3 = str.lines()
  println(separate3)
}

Result:

[bezkoder.com, Programming Tutorials, Web Development]

4. Split String into characters by length

package com.bezkoder.splitstring

fun main(args: Array) {
  val str = "bezkoder"

  val separate4 = str.chunked(3)
  println(separate4)
}

Result:

[bez, kod, er]

4 thoughts to “Kotlin Split String example”

Comments are closed to reduce spam. If you have any question, please send me an email.