0

I have a string that is a version number but I only need the last two digits of the string. I.e, 15.0.4571.1502 -> 4571.1502. I can't seem to figure out an efficient way to do this in Kotlin.

Code:

version = "15.0.4571.1502"

var buildOne = version.split(".").toTypedArray()[2]
var buildTwo = version.split(".").toTypedArray()[3]

var new = "$BuildOne"."$BuildTwo"

Error:

The expression cannot be a selector (occur after a dot)
3
  • 2
    Use var new = "$buildOne.$buildTwo" instead. Commented Jan 26, 2022 at 19:58
  • This isn’t PHP… Commented Jan 26, 2022 at 19:59
  • Nitpick: I think you mean the last two components (or numbers) of the string. The last two digits of your example are 02. Commented Jan 26, 2022 at 23:38

3 Answers 3

7

You've written the dot outside of the string template, the following should work:

val new = "$BuildOne.$BuildTwo"

You can further simplify your solution, by making use of functions provided in the Kotlin standard library.

val version = "15.0.4571.1502"

val new = version
    .split(".")
    .takeLast(2)
    .joinToString(".")
Sign up to request clarification or add additional context in comments.

Comments

5
val version = "15.0.4571.1502"

val new = version.split('.').drop(2).joinToString(".")
// also possible:
// val new = version.split('.').takeLast(2).joinToString(".")

println(new)

Comments

5

Another possible solution using List destructuring:

val version = "15.0.4571.1502"
val (_, _, buildOne, buildTwo) = version.split(".")
val new = "$buildOne.$buildTwo"

Comments

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.