K Lee
K Lee

Reputation: 493

Split space from string is not working in Kotlin

Input is "1 1"

and I want to get this input divide by space

expected output is 1 here, however somehow it is not working.

I read ↓ but could not find a way to fix.

Split space from string not working in Kotlin

fun main(args: Array<String>) {
  val str = readLine()
  val a = str.split("\\s".toRegex())[0]
  println(a)
}
OpenJDK 64-Bit Server VM warning: Options -Xverify:none and -noverify were deprecated in JDK 13 and will likely be removed in a future release.
Main.kt:5:14: error: only safe (?.) or non-null asserted (!!.) calls are allowed on a nullable receiver of type String?
  val a = str.split("\\s".toRegex())[0]

Upvotes: 0

Views: 349

Answers (1)

Adam Millerchip
Adam Millerchip

Reputation: 23137

The problem is written in the error message, you need to replace str.split() with str!!.split():

fun main(args: Array<String>) {
    val str = readLine()
    val a = str!!.split("\\s".toRegex())[0]
    println(a)
}

If you want to print the characters before the first space, you could also do:

str!!.split(" ").first()

Upvotes: 1

Related Questions