format string kotlin android
// extend Long with a suitable function
fun Long.toFormattedString(format: String): String {
// get the Long as String in order to be able to iterate it
val s = this.toString()
// provide a variable for the index
var i = 0
// create an empty result String
var sb: String = ""
// go through the pattern String
for (c in format) {
// replace # with the current cipher
if (c == '#') {
sb += s.get(i)
// increment the counter
i++
} else {
// for every other char in the pattern, just add that char
sb += c
}
}
return sb
}
// try it in a main function
fun main() {
// provide an input and a pattern
val l: Long = 110119225603
val p = "##:##:## ##:##:##"
// print the result of the extension function
print(l.toFormattedString(p))
}