How to get the number of real words in text in Swift

Edit: There is already a question similar to this one, but for numbers separated by a certain character ( Get no words in the quick tool for the calculator ). Instead, this question is going to get the number of real words in the text, separated in different ways: line break, some line breaks, space, more space, etc.

I would like to get the number of words per line with Swift 3.

I use this code, but I get an inaccurate result because the number counts spaces and newlines instead of the effective number of words.

let str = "Architects and city planners,are \ndesigning buildings to create a better quality of life in our urban areas." // 18 words, 21 spaces, 2 lines let components = str.components(separatedBy: .whitespacesAndNewlines) let a = components.count print(a) // 23 instead of 18 
+5
source share
1 answer

Consecutive spaces and newlines are not combined into one common space of spaces, so you just get a bunch of empty β€œwords” between consecutive whitespace characters. Get rid of this by filtering out empty lines:

 let components = str.components(separatedBy: .whitespacesAndNewlines) let words = components.filter { !$0.isEmpty } print(words.count) // 17 

The above text will print 17 because you did not include , as a split character, so the line "planners,are" treated as one word.

You can also break this line by adding punctuation to a set of delimiters, for example:

 let chararacterSet = CharacterSet.whitespacesAndNewlines.union(.punctuationCharacters) let components = str.components(separatedBy: chararacterSet) let words = components.filter { !$0.isEmpty } print(words.count) // 18 

You will now see counter 18 as you expect.

+9
source

Source: https://habr.com/ru/post/1265523/


All Articles