Get the last N characters from a Swift string


This tutorial is going to show how to get the last N characters from a string in Swift. Here we are actually going to create another string by getting the substring that consists of the last N characters.

The easiest way to achieve this task is by using the Swift suffix() method. The suffix() method returns the rest of the substring from the specified position.

Let’s see the code example below:

let siteName = "SwiftSpeedy"

let getLastN = String(siteName.suffix(6))
print(getLastN)

Output:

Speedy

In our example, we have written a program to get the last 6 characters or substring from our Swift string. To get the last 6 characters we have passed 6 as the parameter to the suffix method.

If you would like to get the last 3 characters, then you have to pass 3 to the method:

String(siteName.suffix(3))

Thus you can get the substring of the last N characters from a Swift string. Here N refers to the position from where you want to break the string and get the last one.

Also, read: Get the last character from a string in Swift

Alternative method

Let’s do the same thing using an alternative method.

In this example, we will get the last 6 characters from the same string. Below is the given program for this task:

let siteName = "SwiftSpeedy"

let index = siteName.index(siteName.endIndex, offsetBy: -6)
let getSubString = siteName[index...]

print(getSubString)

Output:

Speedy

As you can see in the above code and from the output, we are able to do the same task, i.e getting the substring consisting of the last 6 characters of our string. In this example, we are not using the suffix() method. Here we are using the string index() method to accomplish the given task.

Using the offsetBy property, we are providing the position from where we want to get the last N characters. In our case, N is 6.