5

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
}
2

4 Answers 4

21

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()
Sign up to request clarification or add additional context in comments.

1 Comment

I Liked it very much because you're doing in Kotlin Way.
3

You can do it like this.. Just make a function of return type list.

 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(), "")
    }

May this will help you :-)

Comments

3

It's easier than you think:

fun stringToWords(mnemonic: String) = mnemonic.replace("\\s+".toRegex(), " ").trim().split(" ")

Remove multiple spaces, trim start and the end, split.
Like an extention:

fun String.toWords() = replace("\\s+".toRegex(), " ").trim().split(" ")

After Roland's suggestion:

fun String.toWords() = trim().split("\\s+".toRegex())

Comments

1

You don't need scopes, the redundant "".toRegex() and the last expression. You can do something like this:

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
}

Additionally, If you use this method a lot in this project, you can make it an extension in string class. Paste this method in a separate file(outside a classes or add it in classless .kt file) so it has a global access. and then you can use it with any string like myString.toWords() anywhere in the project The method will look like this

inline fun String.toWords(): List<String> {
    val words = ArrayList<String>()
    for (w in this.trim(' ').split(" ")) {
        if (w.isNotEmpty()) {
            words.add(w)
        }
    }
    return words
}

1 Comment

Yeah, I heard of Extensions. Great Good Answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.