Kotlin Split String example

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

I. Technology

– Java 1.8
– Kotlin 1.1.2

II. 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

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:

List = CharSequence.split("RegexSyntaxString".toRegex())
2. split() with plain-text characters/strings

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

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

III. Practice

1. split() with Regex
package com.javasampleapproach.splitstring

fun main(args: Array) {
	val str = "ozenero.com = Be Kotlineer - Be Simple - Be Connective"
	
	val separate1 = str.split("=|-".toRegex())
	println(separate1)
}

Result:

[ozenero.com ,  Be Kotlineer ,  Be Simple ,  Be Connective]
2. split() with plain-text characters/strings
package com.javasampleapproach.splitstring

fun main(args: Array) {
	val str = "ozenero.com = Be Kotlineer - Be Simple - Be Connective"
	
	val separate2 = str.split(" = "," - ")
	println(separate2)
}

Result:

[ozenero.com, Be Kotlineer, Be Simple, Be Connective]

2 thoughts on “Kotlin Split String example”

  1. Wow! This could be one particular of the most useful blogs We have ever arrive across on this subject. Basically Wonderful. I’m also an expert in this topic so I can understand your effort.

Leave a Reply

Your email address will not be published. Required fields are marked *