Get the last N characters from a string in Swift
In this tutorial, you will learn how to get the last N characters from a string in Swift with the help of code examples.
To find out the last N characters from our Swift string, we are going to use two different procedures that are listed below:
Using the Swift
suffix() method is the simplest way for getting the last specific number of characters from a string. We just have to pass an integer as an argument that will be the position from where the last characters will be taken. Below is an example of using this method to perform the task:
let website = "CodeSpeedy" let last = String(website.suffix(6)) print(last)
After we run the above code, we will get the result as the output that is given below:
As you can see in the above Swift program, we have passed an integer 6 to the suffix method to get the last 6 characters or substring from our string.
In the program, if you provide 3 to the
suffix() method, then you will able to get the last 3 characters of the string.
You can provide the specific integer number depending on your needs for the method.
Below is another example of getting the substring consisting of the last 4 characters using the string
let city = "Hamburg" let index = city.index(city.endIndex, offsetBy: -4) let subStr = city[index...] print(subStr)
Below is the given output for the above program:
In the above program, we have used the string
index() to get the last 4 characters from the Swift string. In
index(), we have set the
offsetBy property to
-4, which means we want to get the substring for the position
4 from the end.