Kotlin – Split String
Kotlin Split String using a given set of delimiters or Regular Expression – Splitting a string to parts by delimiters is useful when the string contains many (parametric) values separated by delimiters or if the string resembles a regular expression. In this tutorial we shall learn how to split a string in Kotlin using a given set of delimiters or Regular Expression.
*Delimiter is a character or another string that joins multiple strings into a single one.
Example 1 – Split String using Single Delimiter
In the following example, we shall split the string Kotlin TutorialsepTutorial KartsepExamples
with the Delimiter sep
.
example.kt
fun main(args: Array<String>) {
var str = "Kotlin TutorialsepTutorial KartsepExamples"
var delimiter = "sep"
val parts = str.split(delimiter)
print(parts)
}
Output
[Kotlin Tutorial, Tutorial Kart, Examples]
Example 2 – Split String using Multiple Delimiters
Multiple delimiters could be provided as arguments to the split() method of String Class.
String.split(delimiter1, delimiter2, .., delimiterN)
In the following example, we shall split the string Kotlin TutorialsepTutorialasepKartsepExamples
with two delimiters sep
, asep
.
example.kt
fun main(args: Array<String>) {
var str = "Kotlin TutorialsepTutorialasepKartsepExamples"
var delimiter1 = "sep"
var delimiter2 = "asep"
val parts = str.split(delimiter1, delimiter2)
print(parts)
}
Output
[Kotlin Tutorial, Tutorial, Kart, Examples]
Example 3 – Split String Ignoring Case
split() method accepts a boolean value after delimiters, whether to ignore the case of delimiters and the string while splitting.
The default argument for ignoreCase is false. To ignore the case, true has to be provided for the ignoreCase as named argument.
In the following example, we shall split the string Kotlin TutorialsEPTutorialaSEpKartSEpExamples
with two delimiters SEP
, ASEP
.
example.kt
fun main(args: Array<String>) {
var str = "Kotlin TutorialsEPTutorialaSEpKartSEpExamples"
var delimiter1 = "SEP"
var delimiter2 = "ASEP"
val parts = str.split(delimiter1, delimiter2, ignoreCase = true)
print(parts)
}
Output
[Kotlin Tutorial, Tutorial, Kart, Examples]
Example 4 – Split String using Regular Expression
In the following example, we shall split the string Kotlin TutorialsepTutorialasepKartsepExamples
with the Regular Expression sep|asep
.
example.kt
fun main(args: Array<String>) {
var str = "Kotlin TutorialsepTutorialasepKartsepExamples"
val parts = str.split(Regex("sep|asep"))
print(parts)
}
Output
[Kotlin Tutorial, Tutorial, Kart, Examples]
Conclusion
In this Kotlin Tutorial – Kotlin Split String, we have learnt to split string using delimiters, ignoring case, and Regular Expression with examples.