Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get last 4 characters of a string? [duplicate]

Tags:

string

swift

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 
like image 210
do it better Avatar asked Sep 29 '15 17:09

do it better


People also ask

How do I get the last 5 characters of a string?

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.

How do I print the last 3 characters of a string?

string str = "AM0122200204"; string substr = str. Substring(str. Length - 3);

How do I get the last 4 letters of a string in Python?

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.


1 Answers

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)) 
like image 101
vadian Avatar answered Sep 20 '22 07:09

vadian