How to get last 4 characters of a string?

StringSwift

String Problem Overview


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

String Solutions


Solution 1 - String

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))

Solution 2 - String

String substr = a.substring(a.length() - 4)

syntax is wrong. no type before vars in Swift.

let a = "1234567890"
let last4 = String(a.characters.suffix(4))
print(last4)

works on Swift 3.0

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questiondo it betterView Question on Stackoverflow
Solution 1 - StringvadianView Answer on Stackoverflow
Solution 2 - Stringsparsh610View Answer on Stackoverflow