C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Then: I test wordcount with four example strings. I verified that the strings contain the same number of words the method indicates.
Info: The whitespace-only string and the empty string should both contain zero words. The result is as expected.
Ruby program that counts words
def wordcount(value)
# Split string based on one or more whitespace characters.
# ... Then return the length of the array.
value.split(/\s+/).length
end
value = "To be or not to be, that is the question."
puts wordcount(value)
value = "Stately, plump Buck Mulligan came from the stairhead"
puts wordcount(value)
puts wordcount " "
puts wordcount ""
Output
10
8
0
0
So: It may not be intuitive to use split to count words, but this approach is effective and requires little extra code.
Split