I need to seperate the last 4 letters of a string. How can I seperate it? The length of string is changing.
Ex:
var a = "StackOverFlow" var last4 = a.lastFour //That's what I want to do print(last4) //prints Flow
To get the last N characters of a string, call the slice method on the string, passing in -n as a parameter, e.g. str. slice(-3) returns a new string containing the last 3 characters of the original string. Copied! const str = 'Hello World'; const last3 = str.
string str = "AM0122200204"; string substr = str. Substring(str. Length - 3);
The last character of a string has index position -1. So, to get the last character from a string, pass -1 in the square brackets i.e. It returned a copy of the last character in the string. You can use it to check its content or print it etc.
A solution is substringFromIndex
let a = "StackOverFlow" let last4 = a.substringFromIndex(a.endIndex.advancedBy(-4))
or suffix
on characters
let last4 = String(a.characters.suffix(4))
code is Swift 2
Swift 3:
In Swift 3 the syntax for the first solution has been changed to
let last4 = a.substring(from:a.index(a.endIndex, offsetBy: -4))
Swift 4+:
In Swift 4 it becomes more convenient:
let last4 = a.suffix(4)
The type of the result is a new type Substring
which behaves as a String
in many cases. However if the substring is supposed to leave the scope where it's created in you have to create a new String
instance.
let last4 = String(a.suffix(4))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With