How to extract the last 4 characters from NSString?


To extract last 4 characters from a string in swift we can use the internal functions of String class in swift.

With new release every time methods have been modified, deprecated, added and improved in swift. Swift provides different methods to achieve the same. Let’s see these ways of doing it with a few examples.

Method 1 − Substrings

In swift three we were allowed to use a method called substring in which we could pass the string, it’s last index and the offset from which we wanted to trim the string.

Let’s see an example of the same:

var Str1 = "12312$$33@"
print(Str1.substring(from:Str1.index(Str1.endIndex, offsetBy: -4)))

When we run this code, we get the following result.

Method 2 − Suffix

In swift 4, the substring method has been deprecated and now we can use the suffix method of strings, which allow us to get the last few characters of any string.

We can use it like shown below.

print(Str1.suffix(4))

When we run this code, we get the following result.

We can also convert this into a function and use either as an extension of swift or normally in our code.

func getLastFew(range ofCount: Int, from string: String) -> String {
   return String(string.suffix(ofCount))
}

We can use it like shown below.

print(getLastFew(range: 4, from: Str1))

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 30-Jun-2020

707 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements