52

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

Alexander Abakumov
  • 13,617
  • 16
  • 88
  • 129
dpigera
  • 3,339
  • 5
  • 39
  • 60

3 Answers3

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

should do it

Ferruccio
  • 98,941
  • 38
  • 226
  • 299
  • You can also do just state.length instead of [state length] if you prefer. In the end, it's just style, though. (Also this may not be true in older iOS versions) – LarrikJ Mar 02 '12 at 19:50
  • 1
    @LarrikJ: The dot property notation is a feature of Objective-C 2.0. It generates the same code as explicitly sending an accessor message. – Ferruccio Mar 02 '12 at 20:25
1

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

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

Swift 4:

let code = (state as? NSString)?.substring(from: state.characters.count - 2)
Naishta
  • 11,885
  • 4
  • 72
  • 54