how to convert a String sentence to arraylist in Kotlin
我有此功能将字符串句子转换为列表单词。 我使用Java创建了此函数,并使用Android Studio中的默认Kotlin转换将其转换为Kotlin,但是我相信可以通过许多方法来缩短Awesome Kotlin中的这段代码。 如果您可以共享您的代码并帮助我(以及所有人)提高我们对Kotlin的了解,我会很好。
1 2 3 4 5 6 7 8 9 | 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 } |
我会去做以下事情:
1 2 3 | fun stringToWords(s : String) = s.trim().splitToSequence(' ') .filter { it.isNotEmpty() } // or: .filter { it.isNotBlank() } .toList() |
请注意,您可能要调整该过滤器,例如还要过滤掉空白条目...我在注释中放入了该变体...(如果使用该变体,则尽管不需要初始
如果您想使用
正如Abdul-Aziz-Niazi所说:如果您更频繁地使用扩展功能,也可以通过扩展功能实现:
1 | fun String.toWords() = trim().splitToSequence(' ').filter { it.isNotEmpty() }.toList() |
您可以这样操作。.只需创建返回类型列表的函数即可。
1 2 3 4 5 6 7 8 9 | val s ="This is a sample sentence." val words:Array<String> = s.split("\\\\s+".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() for (i in words.indices) { // You may want to check for a non-word character before blindly // performing a replacement // It may also be necessary to adjust the character class words[i] = words[i].replace("[^\\\\w]".toRegex(),"") } |
愿这对您有帮助:-)
它比您想象的要容易:
1 | fun stringToWords(mnemonic: String) = mnemonic.replace("\\\\s+".toRegex(),"").trim().split("") |
删除多个空格,修剪开始和结尾,拆分。
像扩展:
1 | fun String.toWords() = replace("\\\\s+".toRegex(),"").trim().split("") |
根据罗兰的建议:
1 | fun String.toWords() = trim().split("\\\\s+".toRegex()) |
您不需要范围,多余的
您可以执行以下操作:
1 2 3 4 5 6 7 8 9 | private fun stringToWords(mnemonic: String): List<String> { val words = ArrayList<String>() for (w in mnemonic.trim(' ').split("")) { if (w.isNotEmpty()) { words.add(w) } } return words } |
另外,
如果在项目中经常使用此方法,则可以将其作为字符串类的扩展。将此方法粘贴到单独的文件中(在类外部或将其添加到无类.kt文件中),以便可以全局访问。
然后您可以将其与任何字符串一起使用
该方法将如下所示
1 2 3 4 5 6 7 8 9 | inline fun String.toWords(): List<String> { val words = ArrayList<String>() for (w in this.trim(' ').split("")) { if (w.isNotEmpty()) { words.add(w) } } return words } |