如何计算 Kotlin Android 中的单词数? [英] how to count the number of words in Kotlin Android?
问题描述
我曾尝试阅读此线程:
这就是我在代码中使用 first()
的原因,即使它也不起作用.
您遇到的唯一问题是您正在使用
I have tried to read this thread: Android - java - count words
but it doesn't work for me.
so let say I have these words in the android multiline edit text:
I
am
very very
happy
right now
so I want to count the number of words and then get integer '7' from that multiline edit text. how to do that ?
I have tried this, but it doesn't work:
multilineEditText.addTextChangedListener(object: TextWatcher {
override fun afterTextChanged(s: Editable?) {
}
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
val words = s.toString().trim()
numberOfInputWords = words.split("\\s+").first().length
wordsCounterTextView.text = "$numberOfInputWords"
}
})
but this code doesn't work for me, because it doesn't show the right number.
from the thread Android - java - count words
it is said that I can use someString.split("\\s+").length
but I can't access .length
after using .split("\\s+")
. like this
thats why I use first()
in my code, even though it doesn't work either.
The only problem you have is you are using Kotlin's split method which returns a list of String whereas Java's split method returns an array of strings. You should be accessing size property since the return of split method here is List.
val words = s.toString().trim()
numberOfInputWords = words.split("\\s+".toRegex()).size
wordsCounterTextView.text = "$numberOfInputWords"
这篇关于如何计算 Kotlin Android 中的单词数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!