Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to convert a String sentence to arraylist in Kotlin

Tags:

kotlin

I have this function to convert string sentence to list words. I created this function in Java and converted to Kotlin using default Kotlin conversion in Android Studio, but I believe there can be many ways to shorten this code in Awesome Kotlin. I will be good if you can share your piece of code and help me(and all) to improve our knowledge in 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
}
like image 268
januprasad Avatar asked Nov 28 '18 05:11

januprasad


People also ask

How do I convert a string to a List in Kotlin?

To convert a given string into list of characters in Kotlin, call toList() method on this String. toList() returns a List<Char> object with all the characters of this string as elements.

How do I create a custom ArrayList in Kotlin?

Kotlin arrayListOf() Example 3- iterator() function fun main(args: Array<String>){ val list: ArrayList<String> = arrayListOf<String>() list. add("Ajay")


1 Answers

I would go for the following:

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

Note that you probably want to adjust that filter, e.g. to filter out blank entries too... I put that variant in the comment... (if you use that one, you do not require an initial trim() though)

If you rather want to work with the Sequence you can do so by just omitting the .toList() at the end.

And as also Abdul-Aziz-Niazi said: same is also possible via extension function, if you require it more often:

fun String.toWords() = trim().splitToSequence(' ').filter { it.isNotEmpty() }.toList()
like image 152
Roland Avatar answered Nov 11 '22 10:11

Roland