This Kotlin tutorial shows you ways to split string with Kotlin extension functions.
>>> Refer to: JavaSampleApproach.com
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:
1 |
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:
1 |
List<String> = CharSequence.split("RegexSyntaxString".toRegex()) |
2. split() with plain-text characters/strings
Instead of using Regex, you can specify character/string arguments:
1 |
fun CharSequence.split(vararg delimiters: String, ignoreCase: Boolean = false, limit: Int = 0): List<String> |
III. Practice
1. split() with Regex
1 2 3 4 5 6 7 8 |
package com.kotlination.splitstring fun main(args: Array<String>) { val str = "Kotlination.com = Be Kotlineer - Be Simple - Be Connective" val separate1 = str.split("=|-".toRegex()) println(separate1) } |
Result:
1 |
[Kotlination.com , Be Kotlineer , Be Simple , Be Connective] |
2. split() with plain-text characters/strings
1 2 3 4 5 6 7 8 |
package com.kotlination.splitstring fun main(args: Array<String>) { val str = "Kotlination.com = Be Kotlineer - Be Simple - Be Connective" val separate2 = str.split(" = "," - ") println(separate2) } |
Result:
1 |
[Kotlination.com, Be Kotlineer, Be Simple, Be Connective] |