Count the number of words in a Swift string

In this tutorial, you are going to learn how to count the number of total words in a string in Swift programming.

In our example, we have a given string containing some text. We have to find how many words are in the text using Swift programming.

In our example, we will take a string myString and separate it into words. In the end, we will count the words.

Below is given the Swift program that is successfully done our task:

import Foundation

let myString = "I Am Learning Swift Programming"

let strComponents = myString.components(separatedBy: .whitespacesAndNewlines)
let wordsArray = strComponents.filter { !$0.isEmpty }

print(wordsArray.count)  // 5

You can notice that we are using the Foundation framework. This is because the components() method is part of the Foundation framework. So to use, it we must have to import it.

Below I have given the explanation of the above Swift program:

First, we have taken a string and stored it to myString literal.

Next, apply the components() method to our string myString and separate it by white spaces and new lines. With this process, we are getting an array that holds each word as an array element. We store it in strComponents.

After that, we are using the filter() method to remove the array element with an empty value. Off course, empty array elements should not treat as words. Now we have the final array which is wordsArray.

In the end, we are simply using the array count() method to count the array elements. We are directly printing it. This is the actual number of words in our string.

So we have successfully been able to count the total number of words in a given text or string with the help of a few lines of Swift programming.