Created
July 6, 2018 10:19
-
-
Save ElegyD/65ad990d505ee20239ef5a3c16eec951 to your computer and use it in GitHub Desktop.
Counts the number of words in a String
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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