Sling Academy
Home/Swift/Swift: 3 ways to count the occurrences of words in a string

Swift: 3 ways to count the occurrences of words in a string

Last updated: February 23, 2023

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]

Previous Article: Swift: Remove Leading and Trailing Whitespace of a String

Series: Working with Strings in Swift

Swift

You May Also Like

  • How to Find the Union of 2 Sets in Swift
  • How to Find the Intersection of 2 Sets in Swift
  • Subtracting 2 Sets in Swift (with Examples)
  • Swift: Removing Elements from a Set (4 Examples)
  • Swift: Checking if a Set Contains a Specific Element
  • Swift: Counting the Number of Elements in a Set
  • Adding new Elements to a Set in Swift
  • How to Create a Set in Swift
  • Swift: Converting a Dictionary into an Array
  • Merging 2 Dictionaries in Swift
  • Swift: Check if a key exists in a dictionary
  • Swift: Removing a key-value pair from a dictionary
  • Swift: Adding new key-value pairs to a dictionary
  • Swift: Counting Elements in a Dictionary
  • Swift: Ways to Calculate the Product of an Array
  • Swift: How to Convert an Array to JSON
  • Swift: Different ways to find the Min/Max of an array
  • Swift: 4 Ways to Count the Frequency of Array Elements
  • How to Compare 2 Arrays in Swift (Basic & Advanced)