首页 > 解决方案 > 如何在 Kotlin 中将字符串转换为特定格式?

问题描述

在普通语言中,如 C#,它很简单:

long test = 110119225603;
string dateFormat = test.ToString("##:##:## ##:##:##");
Console.WriteLine(dateFormat); // 11:01:19 22:56:03

那么,如何在 Kotlin 中做到这一点?

标签: androidstringkotlinformat

解决方案


您可以利用在 Kotlin 中扩展现有类的可能性并编写一个小的扩展函数来满足您的需求:

// 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))
}

这输出

11:01:19 22:56:03

推荐阅读