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.
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)4
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.