Count number of occurrences of a character in a string in Swift
In this tutorial, I will show you how easily we can count the number of occurrences of a character in a string in Swift.
We can easily count the number of strings using .count
.
let myString = "Hello CodeSpeedy!" print(myString.count)
Output:
17
Using .filter and count
Our goal is to find the number of a specific character in a string. So we can do the below:
let myString = "Hello CodeSpeedy!" print(myString.filter({ $0 == "e"}).count)
Output:
4
This program counts the number of “e” in that string.
So what is happening here is simply filtering out all the “e” from myString
.
Count number of occurrences of a character in a string using .components
Here’s another method:
import Foundation let myString = "Hello CodeSpeedy!" print(myString.components(separatedBy:"e").count - 1)
Output:
4
To understand this clearly, you can take a look at the below program:
import Foundation let myString = "Hello CodeSpeedy!" print(myString.components(separatedBy:"e"))
Output:
["H", "llo Cod", "Sp", "", "dy!"]
So. .components(separatedBy:"e")
is splitting or dividing the string and creating an array with divided substrings.
As we can see, there are 5 elements in the array but the number of the given character is 4. In order to count the number of occurrences of the specific character, we can count the number of elements and subtract 1 or we can simply get the index of the last element of the array and subtract 1.
import Foundation let myString = "Hello CodeSpeedy!" print(myString.components(separatedBy:"e").endIndex-1)
Output:
4
In my opinion, using .filter will be a better option for us if we only want to get the number of occurrences of a character.
You can read: Get the nth character of a string in Swift
Leave a Reply