Kotlin String - split() Function



The Kotlin string split() function is used to divide the string into substrings based on a specified delimiter or set of delimiters.

This function is versatile and allows simple and advanced string separation scenarios, including:

  • Tokenizing strings based on specific delimiters such as: spaces, or commas.
  • Parsing user input.
  • Extracting parts of a structured string like URLs, or file paths.

Syntax

Following is the syntax of the Kotlin string split() function −

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

Parameters

This function accepts following parameters −

  • delimiters: It is a variable number of delimiters used to split the string. These can be strings or characters.
  • ignoreCase: It represents whether the function is case-sensitive or not. If true, the function will accept any alphabet character, whether it is uppercase or lowercase. The default is false.
  • limit: It represent the maximum number of substring to return. Default is 0.

Return value

This function return the list of string.

Example 1: Use Single Delimiter

Following is the basic example of thesplit()function to split with a single delimiter −

fun main() {
   val string = "tutorialsPoint,India,hyderabad"
   // divide the string
   val list = string.split(",")
   println(list)
}

Output

Following is the output −

[tutorialsPoint, India, hyderabad]

Example 2: Use Multiple Delimiter

The following is another example where we use the split() function with multiple delimiters −

fun main() {
   val string = "one,two;three four"
   val list = string.split(",", ";", " ")
   println(list)
}

Output

Following is the output −

[one, two, three, four]

Example 3: Use the Case-Sensitive Character

Here, in this example we use the split() function to split the string with case-sensitive string −

fun main() {
   val string = "HelloTutorialspointhello"
   // use the ignorecase to handle
   //  both upper and lower case letter
   val list = string.split("hello", ignoreCase = true)
   println(list)
}

Output

Following is the output −

[, Tutorialspoint, ]
kotlin_strings.htm
Advertisements