Home »
Kotlin »
Kotlin Programs
Example of split() function in Kotlin
Learn about the split() function in Kotlin, and demonstrate the example of the split() function.
Submitted by IncludeHelp, on March 25, 2022
split() Function
The split() function splits this char sequence to a list of strings around occurrences of the specified delimiters.
Syntax:
fun CharSequence.split(
vararg delimiters: String,
ignoreCase: Boolean = false,
limit: Int = 0
): List<String>
Kotlin program to demonstrate the example of split() function
// Example of split() function
fun main()
{
// Demonstrating split() function
// separate words from white-spaces
val pattern1 = Regex("\\s+")
val res1 : List<String> = pattern1.split("Hello, world! How are you?")
// Prints the words using forEach loop
res1.forEach { term -> println(term) }
println()
// separate words from commas
val pattern2 = Regex(",")
val res2 : List<String> = pattern2.split("Hello,Hi,There")
// Prints the words using forEach loop
res2.forEach { term -> println(term) }
println()
}
Output:
Hello,
world!
How
are
you?
Hello
Hi
There
Kotlin Regular Expression (Regex) Programs »