0

I am trying to retrieve the word count for the text in a UITextView. I can do this already with characters, as in counting the number of letters/spaces, but want the counter to show the number of words instead.

Can't seem to find anything in the documentation, unless it is in there and I don't understand what it is saying.

rmaddy
  • 314,917
  • 42
  • 532
  • 579

2 Answers2

3

To get the word count in a string you can split the string with separator " "(space)

let str = "asd asd asd"

print(str.componentsSeparatedByString(" ").count) // Prints: 3
Arbitur
  • 38,684
  • 22
  • 91
  • 128
0

If you only allow letters:

let str = "one,two"
str.componentsSeparatedByCharactersInSet(NSCharacterSet.letterCharacterSet().invertedSet).count

However in full disclosure this would count words with apostrophes as two words.

Tyrelidrel
  • 354
  • 2
  • 9