dpigera
dpigera

Reputation: 3369

Get last 2 characters of a string?

Say I have a string:

NSString *state = @"California, CA";

Can someone please tell me how to extract the last two characters from this string (@"CA" in this example).

Upvotes: 52

Views: 47304

Answers (3)

Just simply add this extension and use it for String types:

extension String { 
    var last2: String {
        String(self.suffix(2))
    }
}

Upvotes: 1

Naishta
Naishta

Reputation: 12363

Swift 4:

let code = (state as? NSString)?.substring(from: state.characters.count - 2)

Upvotes: 0

Ferruccio
Ferruccio

Reputation: 100648

NSString *code = [state substringFromIndex: [state length] - 2];

should do it

Upvotes: 156

Related Questions