Skip to content

Instantly share code, notes, and snippets.

@ElegyD
Created July 6, 2018 10:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ElegyD/65ad990d505ee20239ef5a3c16eec951 to your computer and use it in GitHub Desktop.
Save ElegyD/65ad990d505ee20239ef5a3c16eec951 to your computer and use it in GitHub Desktop.
Counts the number of words in a String
import java.text.BreakIterator
fun String.countWords(): Int {
fun isWord(word: String): Boolean {
if (word.length == 1) {
return word[0].isLetterOrDigit()
}
return "" != word.trim()
}
val iterator = BreakIterator.getWordInstance()
iterator.setText(this)
var wordCount = 0
var start = 0
var end = iterator.first()
while (end != BreakIterator.DONE) {
val word = substring(start, end)
if (isWord(word)) {
wordCount++
}
start = end
end = iterator.next()
}
return wordCount
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment