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]

1 Answer 1

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()
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, I read the error too and tried 「str?.split("\\s".toRegex())[0]」but did not work, what is the difference between ? & !! ?
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.