MST
星途 面试题库

面试题:Kotlin字符串拼接与格式化

在Kotlin中,给定两个字符串变量 `str1` 和 `str2`,以及一个整数变量 `num`。要求使用字符串模板和 `format` 函数两种方式,将这三个值拼接成一个新的字符串,格式为:`str1的值:str2的值:num的值`。例如,`str1`为`'hello'`,`str2`为`'world'`,`num`为`10`,则结果为`'hello:world:10'`。请写出完整的代码实现。
48.6万 热度难度
编程语言Kotlin

知识考点

AI 面试

面试题答案

一键面试
fun main() {
    val str1 = "hello"
    val str2 = "world"
    val num = 10

    // 使用字符串模板
    val resultByTemplate = "$str1:$str2:$num"
    println(resultByTemplate)

    // 使用format函数
    val resultByFormat = String.format("%s:%s:%d", str1, str2, num)
    println(resultByFormat)
}