将一个字符串拆分成每个字符串2个字符的惯用方式是什么?

Examples:

"" -> [""]
"ab" -> ["ab"]
"abcd" -> ["ab", "cd"]

我们可以假设字符串的长度是2的倍数.

I could use a regex like in this Java answer but I was hoping to find a better way (i.e. using one of kotlin's additional methods).

推荐答案

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)

You can already try this with Kotlin 1.2 M2 pre-release.


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]

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

Kotlin相关问答推荐

如何为集成测试配置Gradle JVM测试套件?

如何在Kotlin中为接受varargs的函数添加带有默认值的新参数?

Webpack 配置未应用于 kotlin 多平台react 项目

在 kotlin 原始字符串中转义三重引号

在kotlin中匹配多个变量

Jetpack compose 可滚动表格

内联函数导致单元测试代码覆盖率报告出错

SpringBoot 2.5.0 对于 Jackson Kotlin 类的支持,请在类路径中添加com.fasterxml.jackson.module: jackson-module-kotlin

Kotlin-Java 互操作不能与可变参数一起使用

如何在 android jetpack compose 中相互重叠列表项?

如何在 Kotlin 中使用 volatile

如何在 Kotlin 中创建一个打开新活动(Android Studio)的按钮?

Kotlin:如何修改成对的值?

Kotlin:相互递归函数的尾部递归

无法解决:androidx.lifecycle:lifecycle-extensions-ktx:2.0.0-alpha1

Kotlin数据类打包

内联 onFocusChange kotlin

Kotlin类型安全类型别名

尾随 lambda 语法(Kotlin)的目的是什么?

Dagger 2 androidx fragment不兼容类型