Home > Enterprise >  Kotlin - Split string into new string
Kotlin - Split string into new string

Time:01-27

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)

CodePudding user response:

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(".")

CodePudding user response:

val version = "15.0.4571.1502"

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

println(new)
  •  Tags:  
  • Related