How to find String length in Swift

swift Oct 11, 2024
length of string in swift

Counting characters in a string is a common requirement in many applications. This article covers finding the total number of characters in a string as well as the multiple approaches to find a specific substring in a given string.

Table of Contents

  1. How to find length of a String in Swift
  2. How to find length of a substring in Swift

 

How to find the length of a String in Swift

To count the number of characters in a given string, you simply have to use an in-built Swift method `count` which returns the total length of the string. Spaces are also counted as characters when calculating the length.

let name = "SwiftAnytime"
print("Length of the string is \(name.count)")

Output:

Length of the string is 12

 

How to find length of a substring in Swift

There are primarily two approaches to count the number of substring in a given string. To make the examples a bit more interesting, we have taken some tongue twisters.

First Approach:

You can use the ranges(of:) method which gives the ranges of all the occurrences of a given substring in a string and the search is case-sensitive. Since it only gives the range, you also have to count the number of such ranges found, using the .count method.

let text = "She sells seashells by the seashore"

let substringCount = text.ranges(of: "sea").count

print("The substring 'sea' appears \(substringCount) times.")

Output:

The substring 'sea' appears 2 times.

 

Second Approach:

Another approach is to use the components(separatedBy:) method. This method divides the complete string into parts based on the character or the substring passed to it and return an array containing the substrings.

You can then count the number of elements in the array to find the number of substrings in the given string.

let text = "I slit the sheet, the sheet I slit, and on the slitted sheet I sit."

let characterCount = text.components(separatedBy: "I").count - 1
let substringCount = text.components(separatedBy: "slit").count - 1

print("The character 'I' appears \(characterCount) times.")
print("The substring 'slit' appears \(substringCount) times.")

Output:

The character 'I' appears 3 times.
The substring 'slit' appears 3 times.

Note: The number of components in the resulting array is always one more than the number of occurrences of the substring, that is the reason why 1 is subtracted from the actual count.

 

Where to go next?

Congratulations on making it through this comprehensive guide on Swift text character counting. We would highly recommend you to read about more articles like For loop in Swift and ProgressView in SwiftUI.

Signup now to get notified about our
FREE iOS Workshops!