Word Count Function
This page was last reviewed on Sep 2, 2023.
Dot Net Perls
Word count. Sometimes a document may have a certain file size, but the word count is clearer for estimating its length. A function that counts words in Swift can be developed.
With a for-loop over the characters, we can test each character with Character type properties. Some logic is required to test for whitespace.
Example. We introduce the countWords function. This function receives a String and returns an Int—the count of words in the string.
Step 1 We loop over the characters in the string. The for-loop returns each value as a Character type.
Step 2 We test the previous character to see if it is whitespace that could start a word. We also test the current character for a letter.
Step 3 Because we have to test two characters at once on each iteration, we need to set the previous character here.
Step 4 We return the total number of words in the string, based on the result of the iterative function.
func countWords(source: String) -> Int { var count = 0 var previous: Character = " " // Step 1: loop over string characters. for c in source { // Step 2: test previous character for whitespace, and current for letter, number or punctuation. if previous.isWhitespace { if c.isLetter || c.isNumber || c.isPunctuation { count += 1 } } // Step 3: set previous. previous = c } // Step 4: return count of words. return count } // Use word counting function. let input = "Cat, bird and dog." let result = countWords(source: input) print(result)
Summary. It is possible to develop an iterative word count algorithm in Swift, and this gives accurate results for English. It is also fast, as no regular expressions are used.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Sep 2, 2023 (new).
© 2007-2024 Sam Allen.