Count number of characters in a string in Swift

In this tutorial, we will discuss how to count the number of characters in a given string in Swift. This task comes under the chapter on strings which is proved to be one of the useful tasks when we need to count the number of characters in a given string.

Example-

String 1 -“CodeSpeedy”

Number of characters- 10

String 2 – “Character”

Number of characters-9

Method 1- Counting the number of characters in a string

In this method, we will focus on how to count the number of characters in a given String. For this, we use count which counts the number of characters in a given string. Let’s try to count the number of characters in the string Hello and CodeSpeedy-

var message: String = "Hello"
var name: String = "CodeSpeedy"

print(message.count)
print(name.count)
5
10

Here we can see that we have two strings and printed the total count

Method 2- Counting distinct characters in a given string

As far as we know, we have discussed how to count the number of characters in a given string but now we will focus on counting distinct characters when we need to ignore the same characters-

var message: String = "Hello"
var name: String = "CodeSpeedy"


print(Set(message).count)
print(Set(name).count)
4
7

Method 3- Counting a specific character in a given string

When we need to count a specific character, (like the number of times it is repeated in a given string) is needed to be counted many times while practical applications of strings-

var message: String = "Hello"
var name: String = "CodeSpeedy"

print(name.filter { $0 == "e" }.count)
3

So here we have also checked for occurrences of a particular character in a given string.

In this tutorial, we have discussed counting the characters in a given string. I hope you liked this tutorial!

Also read: Count number of occurrences of a character in a string in Swift

Leave a Reply

Your email address will not be published. Required fields are marked *