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
  • 307,833
  • 40
  • 508
  • 550

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
  • 37,971
  • 22
  • 89
  • 126
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
  • 364
  • 2
  • 9