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 = "grokonez.com = Be Kotlineer - Be Simple - Be Connective"
	
	val separate1 = str.split("=|-".toRegex())
	println(separate1)
}

Result:

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

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

Result:

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


By grokonez | August 29, 2017.


Related Posts


Got Something To Say:

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

*