This concise, example-based article walks you through 3 different approaches to counting the occurrences of words in a given string in Swift. Without wasting any more time, let’s dive in.
Using Dictionary and For Loop
One way to count the occurrences of words in a string is to use a dictionary and a for loop. I will show you an example and then explain the code later.
Example:
import Foundation
let str = "My dog is a big dog. My dog is a good dog."
let words = str.components(separatedBy: .whitespacesAndNewlines)
var wordCount = [String: Int]()
for word in words {
if let count = wordCount[word] {
wordCount[word] = count + 1
} else {
wordCount[word] = 1
}
}
print(wordCount)
Output:
["a": 2, "dog": 2, "dog.": 2, "is": 2, "good": 1, "My": 2, "big": 1]
In the code above, we first split the string into an array of words using the components(separatedBy:) method. We then create an empty dictionary to store the word counts. Finally, we iterate over each word in the array, checking if it already exists in the dictionary. If it does, we increment its count; if it doesn’t, we add it to the dictionary with a count of 1.
Using NSCountedSet
Another way to count the occurrences of words in a string is to use an NSCountedSet.
Example:
import Foundation
let str = "Hello, World! Hello, Swift!"
let words = str.components(separatedBy: .whitespacesAndNewlines)
let countedSet = NSCountedSet(array: words)
let wordCount = countedSet.reduce(into: [:]) { dict, element in
dict[element as! String] = countedSet.count(for: element)
}
print(wordCount)
Output:
["Swift!": 1, "World!": 1, "Hello,": 2]
In the example above,
In this code, we again split the string into an array of words. We then create an NSCountedSet from the array, which automatically counts the occurrences of each word. Finally, we use the reduce(into:) method to convert the NSCountedSet to a dictionary.
Using Regular Expressions
Regular expressions are powerful. Today, we’ll make use of them to find the occurrences of words in a given string in Swift ((it looks more complicated than the 2 preceding techniques, but it is very flexible and can be easily customized for special cases).
Example:
import Foundation
let str = "Welcome to Sling Academy and welcome to the land of programmin"
let pattern = "\\w+"
let regex = try! NSRegularExpression(pattern: pattern)
let matches = regex.matches(in: str, range: NSRange(str.startIndex..<str.endIndex, in: str))
var wordCount = [String: Int]()
for match in matches {
let range = match.range(at: 0)
if let swiftRange = Range(range, in: str) {
let word = str[swiftRange].lowercased()
wordCount[word, default: 0] += 1
}
}
print(wordCount)
Output:
["welcome": 2, "sling": 1, "to": 2, "of": 1, "programmin": 1, "academy": 1, "and": 1, "the": 1, "land": 1]