首页 > 解决方案 > 如何在 Kotlin 中将字符串语句转换为数组列表

问题描述

我有这个函数可以将字符串句子转换为列表单词。我在 Java 中创建了这个函数,并在 Android Studio 中使用默认的 Kotlin 转换转换为 Kotlin,但我相信在 Awesome Kotlin 中可以有很多方法来缩短这个代码。如果你能分享你的代码并帮助我(和所有人)提高我们在 Kotlin 中的知识,我会很好。

private fun stringToWords(mnemonic: String): List<String> {
    val words = ArrayList<String>()
    for (word in mnemonic.trim { it <= ' ' }.split(" ".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()) {
        if (word.isNotEmpty()) {
            words.add(word)
        }
    }
    return words
}

标签: kotlin

解决方案


我会去以下:

fun stringToWords(s : String) = s.trim().splitToSequence(' ')
    .filter { it.isNotEmpty() } // or: .filter { it.isNotBlank() }
    .toList()

请注意,您可能想要调整该过滤器,例如也过滤掉空白条目...我将该变体放在评论中...(如果您使用该变体,则不需要初始trim()值)

如果您更愿意使用 the ,您可以通过在末尾Sequence省略 the 来做到这一点。.toList()

正如 Abdul-Aziz-Niazi 所说:同样也可以通过扩展功能实现,如果您更频繁地需要它:

fun String.toWords() = trim().splitToSequence(' ').filter { it.isNotEmpty() }.toList()

推荐阅读