0

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]
K Lee
  • 473
  • 3
  • 16

1 Answers1

1

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()
Adam Millerchip
  • 20,844
  • 5
  • 51
  • 74
  • Thank you, I read the error too and tried 「str?.split("\\s".toRegex())[0]」but did not work, what is the difference between ? & !! ? – K Lee Jan 16 '21 at 13:50
  • 1
    `str?.split("\\s".toRegex())?.get(0)`. `readLine` can be `null`. `!!` means that you are saying it will never be null, `.?` will only be executed if the value before it is not null, otherwise it will return null. – Adam Millerchip Jan 16 '21 at 13:54