2

How can I substring an NSString with the last x characters? Right to left.

In python it takes only one line!

>>> "string"[-4:]
'ring'
Martino
  • 103
  • 1
  • 7
  • 1
    [String Programming Guide: Combining and Extracting Strings](http://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Strings/Articles/CreatingStrings.html#//apple_ref/doc/uid/20000148-SW5) | [`NSString` Class Reference](http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html) – jscs Jan 11 '12 at 00:17

4 Answers4

16

It should be a one liner in Objective-C, too:

NSString *substring = [string substringFromIndex:[string length] - x];
Carl Norum
  • 219,201
  • 40
  • 422
  • 469
1

You can find the answer you're looking for by checking out the documentation for NSString from the apple.developer.com website.

Specifically, you can use the substringFromIndex: method.

For example, if you already have a string called originalString and you want to obtain a string that has the last x characters. You can do:

NSString* slicedString = [originalString substringFromIndex: originalString.length-x]

This should return a string with the last x characters.

Bitwise
  • 565
  • 5
  • 8
0
int index = **Some integer value**
    NSString *string = [originalString substringFromIndex:index];
    NSString *string = [originalString substringToIndex:index];
Dani Pralea
  • 4,545
  • 2
  • 31
  • 49
0
NSString *substring = [initialstring substringFromIndex:[intialstring length] - x];
dgund
  • 3,459
  • 4
  • 39
  • 64