Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
374 views
in Technique[技术] by (71.8m points)

ios - 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?

}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...