如何从NSString中捕获最后4个字符 [英] How to capture last 4 characters from NSString
问题描述
我接受来自 UITextField $ c的随机
尺寸
的 NSString
$ c>并将其传递给我正在创建的方法,该方法仅捕获字符串中输入的最后4个字符
。
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
.
我查看了 NSString
类参考库,我发现的唯一真实选项看起来就像我想做的那样
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.
到目前为止,这是我创建的方法,它传递的是 NSString
来自IBAction其他地方。
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?
}
推荐答案
使用substringFromIndex方法,
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))
这篇关于如何从NSString中捕获最后4个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!