且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

每n个字符分割一次字符串

更新时间:2022-12-28 16:14:03

发布Kotlin 1.2后,您可以使用kotlin-stdlib的chunked函数. .com/Kotlin/KEEP/blob/master/proposals/stdlib/window-sliding.md"rel =" noreferrer> KEEP-11 提案.示例:

Once Kotlin 1.2 is released, you can use the chunked function that is added to kotlin-stdlib by the KEEP-11 proposal. Example:

val chunked = myString.chunked(2)

您已经可以使用科特琳1.2 M2预发布.

在此之前,您可以使用以下代码实现相同的操作:

Until then, you can implement the same with this code:

fun String.chunked(size: Int): List<String> {
    val nChunks = length / size
    return (0 until nChunks).map { substring(it * size, (it + 1) * size) }
}

println("abcdef".chunked(2)) // [ab, cd, ef]

此实现删除了少于size元素的其余部分.您可以对其进行修改,也将余数也添加到结果中.

This implementation drops the remainder that is less than size elements. You can modify it do add the remainder to the result as well.