kotlin - 如何在 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
}
解决方案
我会去以下:
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()
推荐阅读
- mongodb - 将制表符分隔的文本文件放入 MongoDB 集合的最佳方法
- android - 单击按钮时未弹出权限框-Android Studio
- node.js - NodeJs MongoDB如何发出复杂的GET请求
- sql-server - 想要从 SQL Server 数据库中删除旧条目
- prometheus - 了解 Prometheus 中的速率函数值
- typescript - 无法解决/拒绝 Promise
- python - pySpark:ConnectionResetError: [WinError 10054] 现有连接被远程主机强行关闭
- .htaccess - 编写 htaccess 规则的问题
- python - OpenCV 中的 Python 线程
- excel - 跨多个工作表操作数据