How to capture last 4 characters from NSString

别等时光非礼了梦想. 提交于 2019-11-27 11:19:56

问题


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?

}

回答1:


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



回答2:


Try This,

NSString *lastFourChar = [yourNewString substringFromIndex:[yourNewString length] - 4];



回答3:


The Swift answer provided by KingOfBliss is producing an error for me as of XCode 7.3, and should not be used going forward due to bridging to NS classes, which should be removed in Swift 3.0.

A better example that considers an invalid range, as well as the possibility of special characters to provide the right spot to remove:

The string in question: Voulez-vous un café?

var trimmedString = "Voulez-vous un caf\u{65}\u{301}?"

let stringSize = trimmedString.characters.count
let startIndex = 4

if stringSize >= startIndex {
    let range = trimmedString.endIndex.advancedBy(-startIndex)..<trimmedString.endIndex
    trimmedString.removeRange(range)
}

This will produce an answer of Voulez-vous un c.

By accessing the string with the start & end index values, you protect against situations where not all chars are the same size (ex: \u{65}\u{301})



来源:https://stackoverflow.com/questions/6591538/how-to-capture-last-4-characters-from-nsstring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!