How to capture last 4 characters from NSString
Asked Answered
G

3

35

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?

}
Gay answered 6/7, 2011 at 4:25 Comment(0)
C
97

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))
Czarina answered 6/7, 2011 at 4:27 Comment(4)
that gives me a warning saying (instance method subStringFromIndex not found type defaults to 'id')Gay
Ah, its substringFromIndex not subStringFromIndex, case sensitive :) thanks alot KingofblissGay
Actually, you should probably protects yourself by using: NSString *trimmedString=[string substringFromIndex:MAX((int)[string length]-4, 0)]; in case string is less than 4 characters long.Isidore
Some loose thoughts: 1.) do not call [substringFromIndex:] unless necessary, 2.) NSString [length] is declared as @property so use the dot notation, 3.) Type-emphasized pointer style forever! ;) NSString* trimmedString = string.length > 4 ? [string substringFromIndex:(string.length - 4)] : string;Nigeria
T
10

Try This,

NSString *lastFourChar = [yourNewString substringFromIndex:[yourNewString length] - 4];
Tetracycline answered 18/4, 2015 at 11:37 Comment(0)
P
0

You can check this function in Swift 5:

func subString(from myString: NSString, length: Int) {
    let myNSRange = NSRange(location: myString.length - length, length: length)
    print(myString.substring(with: myNSRange))
}
subString(from: "Menaim solved the issue", length: 4) // Output: ssue
Powerful answered 7/12, 2020 at 17:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.