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)
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
If you would like to get the last 3 characters, then you have to pass 3 to the method:
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
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)
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.
offsetBy property, we are providing the position from where we want to get the last N characters. In our case, N is 6.