How to get the number of real words in a text in Swift [duplicate]
Consecutive spaces and newlines aren't coalesced into one generic whitespace region, so you're simply getting a bunch of empty "words" between successive whitespace characters. Get rid of this by filtering out empty strings:
let components = str.components(separatedBy: .whitespacesAndNewlines)let words = components.filter { !$0.isEmpty }print(words.count) // 17
The above will print 17
because you haven't included ,
as a separation character, so the string "planners,are"
is treated as one word.
You can break that string up as well by adding punctuation characters to the set of separators like so:
let chararacterSet = CharacterSet.whitespacesAndNewlines.union(.punctuationCharacters)let components = str.components(separatedBy: chararacterSet)let words = components.filter { !$0.isEmpty }print(words.count) // 18
Now you'll see a count of 18
like you expect.