从NSString中提取数字 NSScanner

-(int)findNumFromStr
{
    NSString *originalString = @"a1b2c3d4e5f6g7h8i9j";
    
    // Intermediate
    NSMutableString *numberString = [[[NSMutableString alloc] init] autorelease];
    NSString *tempStr;
    NSScanner *scanner = [NSScanner scannerWithString:originalString];
    NSCharacterSet *numbers = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
    
    while (![scanner isAtEnd]) {
        // Throw away characters before the first number.
        [scanner scanUpToCharactersFromSet:numbers intoString:NULL];
        
        // Collect numbers.
        [scanner scanCharactersFromSet:numbers intoString:&tempStr];
        [numberString appendString:tempStr];
        tempStr = @"";
    }
    // Result.
    int number = [numberString integerValue];
    
    return number;
}


使用NSScanner类

- (NSString *)string;
- (NSUInteger)scanLocation;
- (void)setScanLocation:(NSUInteger)pos;//设置开始扫描的位置
- (void)setCharactersToBeSkipped:(NSCharacterSet *)set;//扫描的时候需要忽略的值
- (void)setCaseSensitive:(BOOL)flag; //是否区分大小写
- (void)setLocale:(id)locale; //大概意思是不同语言环境解释字符串的方式不一样,不懂
- (NSCharacterSet *)charactersToBeSkipped; //扫描时所有被忽略的值
- (BOOL)caseSensitive;
- (id)locale;

- (BOOL)scanInt:(int *)value;  //是否找到一个十进制 int
- (BOOL)scanInteger:(NSInteger *)value NS_AVAILABLE(10_5, 2_0);  //是否找到一个十进制 NSInteger
- (BOOL)scanHexLongLong:(unsigned long long *)result NS_AVAILABLE(10_5, 2_0);   //是否找到16进制的long long类型的数字
- (BOOL)scanHexFloat:(float *)result NS_AVAILABLE(10_5, 2_0);		// Corresponding to %a or %A formatting. Requires "0x" or "0X" prefix. 
- (BOOL)scanHexDouble:(double *)result NS_AVAILABLE(10_5, 2_0);		// Corresponding to %a or %A formatting. Requires "0x" or "0X" prefix. 
- (BOOL)scanHexInt:(unsigned *)value;		// Optionally prefixed with "0x" or "0X"
- (BOOL)scanLongLong:(long long *)value;
- (BOOL)scanFloat:(float *)value;
- (BOOL)scanDouble:(double *)value;

- (BOOL)scanString:(NSString *)string intoString:(NSString **)value; //从scan中扫描出set中的数据放入value中

- (BOOL)scanCharactersFromSet:(NSCharacterSet *)set intoString:(NSString **)value;//从scan中扫描出set中的数据放入value中
- (BOOL)scanUpToString:(NSString *)string intoString:(NSString **)value;//从scan中扫描出set之外的数据放入value中
- (BOOL)scanUpToCharactersFromSet:(NSCharacterSet *)set intoString:(NSString **)value;//从scan中扫描出set之外的数据放入value中
- (BOOL)isAtEnd;//是否扫描达到终点

- (id)initWithString:(NSString *)string;
+ (id)scannerWithString:(NSString *)string;
+ (id)localizedScannerWithString:(NSString *)string;


你可能感兴趣的:(从NSString中提取数字 NSScanner)