'Kotlin - Split string into new string
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)
Solution 1:[1]
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(".")
Solution 2:[2]
val version = "15.0.4571.1502"
val new = version.split('.').drop(2).joinToString(".")
// also possible:
// val new = version.split('.').takeLast(2).joinToString(".")
println(new)
Solution 3:[3]
Another possible solution using List destructuring:
val version = "15.0.4571.1502"
val (_, _, buildOne, buildTwo) = version.split(".")
val new = "$buildOne.$buildTwo"
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Endzeit |
| Solution 2 | lukas.j |
| Solution 3 | Arpit Shukla |
