How could I split a String into an array in Kotlin?

Solution 1:

val strs = "name, 2012, 2017".split(",").toTypedArray()

Solution 2:

If we have a string of values that splited by any character like ",":

 val values = "Name1 ,Name2, Name3" // Read List from somewhere
 val lstValues: List<String> = values.split(",").map { it -> it.trim() }
 lstValues.forEach { it ->
                Log.i("Values", "value=$it")
                //Do Something
            }

It's better to use trim() to delete spaces around strings if exist. Consider that if have a "," at the end of string it makes one null item, so can check it with this code before split :

 if ( values.endsWith(",") )
     values = values.substring(0, values.length - 1)

if you want to convert list to Array ,use this code:

      var  arr = lstValues.toTypedArray()
      arr.forEach {  Log.i("ArrayItem", " Array item=" + it ) }

Solution 3:

Simple as it is:

val string: String = "leo_Ana_John"
val yourArray: List<String> = string.split("_")

you get: yourArray[0] == leo, yourArray[1] == Ana, yourArray[2]==John

In this case, just change the "_" from my code to ", " of yours. Se bellow

    val yourArray: List<String> = string.split(", ")

Solution 4:

Split a string using inbuilt split method then using method extensions isNum() to return numeric or not.

fun String.isNum(): Boolean{
   var num:Int? = this.trim().toIntOrNull()
   return if (num != null) true else false
}

for (x in "name, 2012, 2017".split(",")) {
   println(x.isNum())
}

Solution 5:

var mString = "853 kB"
val mString = newSize!!.split(" ").toTypedArray()

Here Split parameter is space

mString.get(0) = "853"
mString.get(1) = "kB"