English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Kotlin splits strings using a given set of delimiters or regular expressions-It is very useful to split a string into multiple parts using a delimiter when the string contains many (parameter) values separated by delimiters or when the string is similar to a regular expression. In this tutorial, we will learn how to split strings in Kotlin using the given delimiter or regular expression.
* A delimiter is a character or another string that connects multiple strings into a single string.
In the following example, we will split the string "stringKotlin TutorialsepTutorialsepw" using the delimiter sep3codebox.com.
fun main(args: Array<String>) { var str = "Kotlin TutorialsepTutorial Kotlinsepw"3codebox.com var delimiter = "sep" val parts = str.split(delimiter) print(parts) }
Output Result:
[Kotlin Tutorial, Tutorial Kotlin, w}3codebox.com]
You can also provide multiple delimiters as parameters for the String class's split() method. The syntax is as follows:
String. split(delimiter1, delimiter2, .., delimiterN)
In the following example, we will use two delimiters sep, asep to split the string Kotlin TutorialsepTutorialasepoldtoolbag.comsepExamples Example.
fun main(args: Array<String>) { var str = "Kotlin TutorialsepTutorialasepoldtoolbag.comsepExamples" var delimiter1 = "sep" var delimiter2 = "asep" val parts = str.split(delimiter1, delimiter2) print(parts) }
Output Result:
[Kotlin Tutorial, Tutorial, oldtoolbag.com, Examples]
The split () method accepts a boolean value as the second parameter after the delimiter, which is used to determine whether to ignore the case of the delimiter and the string during the split.
String. split(vararg delimiters, ignoreCase:Boolean = false)
The default parameter for ignoreCase is false. To ignore case, you must provide true as a named parameter to ignoreCase. In the following example, we will use two delimiters SEP, ASEP to split the string stringKotlin TutorialsEPTutorialaSEpKotlinSEpExamples.
fun main(args: Array<String>) { var str = "Kotlin TutorialsEPTutorialaSEpKotlinSEpExamples" var delimiter1 = "SEP" var delimiter2 = "ASEP" val parts = str.split(delimiter1, delimiter2, ignoreCase = true) print(parts) }
Output Result:
[Kotlin Tutorial, Tutorial, Kotlin, Examples]
In the following example, we will use the regular expression sep|asep to split the string Kotlin TutorialsepTutorialasepKotlinsepExamples.
fun main(args: Array<String>) { var str = "Kotlin TutorialsepTutorialasepKotlinsepExamples" val parts = str.split(Regex("sep|asep")) print(parts) }
Output Result:
[Kotlin Tutorial, Tutorial, Kotlin, Examples]
In this Kotlin tutorial-In this Kotlin tutorial, we have learned how to split strings using delimiters, ignoring case, and with examples of regular expressions.