How to split a String into an array in Kotlin?


In this article, we will take a couple of examples to demonstrate how we can split a given String in Kotlin using some given delimiters.

Example – Split a String using given delimiters

In this example, we will create a String and we will store some value in it and we will try to split the same using some delimiters.

fun main(args: Array<String>) {

   var str = "Tut@or@ia@lsPo@int.@com"
   var delimiter = "@"

   // It will split the given String using '@'
   val parts = str.split(delimiter)

   print(parts)

}

Output

It will generate the following output −

[Tut, or, ia, lsPo, int., com]

Example – Split a String using multiple delimiters

fun main(args: Array<String>) {

   var str = "Tu#t@or@ia#@lsP#o@int.@com"

   // passing multiple delimiters
   val parts = str.split("#","@")

   print(parts)

}

Output

On execution, it will produce the following output −

[Tu, t, or, ia, , lsP, o, int., com]

Updated on: 01-Mar-2022

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements