Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to capture last 4 characters from NSString

I am accepting an NSString of random size from a UITextField and passing it over to a method that I am creating that will capture only the last 4 characters entered in the string.

I have looked through NSString Class Reference library and the only real option I have found that looks like it will do what I want it to is

- (void)getCharacters:(unichar *)buffer range:(NSRange)aRange 

I have used this once before but with static parameters 'that do not change', But for this implementation I am wanting to use non static parameters that change depending on the size of the string coming in.

So far this is the method I have created which is being passed a NSString from an IBAction else where.

- (void)padString:(NSString *)funcString {      NSString *myFormattedString = [NSString stringWithFormat:@"%04d",[funcString intValue]]; // if less than 4 then pad string     //   NSLog(@"my formatedstring = %@", myFormattedString);      int stringLength = [myFormattedString length]; // captures length of string maybe I can use this on NSRange?       //NSRange MyOneRange = {0, 1}; //<<-------- should I use this? if so how?  } 
like image 910
C.Johns Avatar asked Jul 06 '11 04:07

C.Johns


People also ask

How would you extract the last four characters from a string?

Method 1: SUBSTR() & LENGTH() functions To extract the last 4 characters from a string, you need to set the position argument of the SUBSTR() function to the fourth to last position of your string (you can omit the length argument). By definition, the fourth to last position of a string is its length minus 3.

What is the difference between NSString and string?

NSString is a classSwift is interoperatable with Objective-C and converts some Objective-C types to Swift types. Types that can be converted between Obj-C and Swift are known as bridged types. String and NSString are example of such bridged types and hence you can assign NSString to a String variable.

What does NSString mean?

A static, plain-text Unicode string object that bridges to String ; use NSString when you need reference semantics or other Foundation-specific behavior.


2 Answers

Use the substringFromIndex method,

OBJ-C:

NSString *trimmedString=[string substringFromIndex:MAX((int)[string length]-4, 0)]; //in case string is less than 4 characters long. 

SWIFT:

let trimmedString: String = (s as NSString).substringFromIndex(max(s.length-4,0)) 
like image 174
KingofBliss Avatar answered Sep 28 '22 17:09

KingofBliss


Try This,

NSString *lastFourChar = [yourNewString substringFromIndex:[yourNewString length] - 4]; 
like image 36
Yash Joshi Avatar answered Sep 28 '22 18:09

Yash Joshi