如何使用NSScanner?

时间:2009-02-27 13:42:05

标签: objective-c string cocoa parsing nsscanner

我刚读过Apple的docu NSScanner。 我正在尝试获取该字符串的整数:@“用户登录(3次尝试)”。

我找不到任何例子,如何在括号内扫描。有什么想法吗?

以下是代码:

NSString *logString = @"user logged (3 attempts)";
NSScanner *aScanner = [NSScanner scannerWithString:logString];

[aScanner scanInteger:anInteger];

NSLog(@"Attempts: %i", anInteger);

5 个答案:

答案 0 :(得分:50)

Ziltoid的解决方案有效,但它的代码比你需要的多。

对于给定的情况,我不打算实例化NSScanner。 NSCharacterSet和NSString为您提供所需的一切:

    NSString *logString = @"user logged (3 attempts)";
    NSString *digits = [logString stringByTrimmingCharactersInSet:
         [[NSCharacterSet decimalDigitCharacterSet] invertedSet]];
    NSLog(@"Attempts: %i", [digits intValue]);

或在Swift中:

    let logString = "user logged (3 attempts)"
    let nonDigits = NSCharacterSet.decimalDigitCharacterSet().invertedSet
    let digits : NSString = logString.stringByTrimmingCharactersInSet(nonDigits)
    NSLog("Attempts: %i", digits.intValue)

答案 1 :(得分:17)

`这是我从字符串中获取某些值的方法

首先我定义了这个方法

- (NSString *)getDataBetweenFromString:(NSString *)data leftString:(NSString *)leftData rightString:(NSString *)rightData leftOffset:(NSInteger)leftPos; 
{         
    NSInteger left, right;         
    NSString *foundData;
    NSScanner *scanner=[NSScanner scannerWithString:data];                  
    [scanner scanUpToString:leftData intoString: nil];         
    left = [scanner scanLocation];         
    [scanner setScanLocation:left + leftPos];         
    [scanner scanUpToString:rightData intoString: nil];         
    right = [scanner scanLocation] + 1;         
    left += leftPos;         
    foundData = [data substringWithRange: NSMakeRange(left, (right - left) - 1)];         return foundData; 
}

然后打电话。

foundData = [self getDataBetweenFromString:data leftString:@"user logged (" rightString:@"attempts)" leftOffset:13];

leftOffset是左侧字符串的字符数

可能是一种更简单的清洁方式,但那是我的解决方案。

答案 2 :(得分:5)

NSScanner是线性扫描仪。你必须扫描你不想达到你想要的东西。

你可以[aScanner scanUpToCharactersInSet:[NSCharacterSet decimalDigitCharacterSet] intoString:NULL]跳过所有数字字符。然后执行[aScanner scanInteger:&anInteger]将字符扫描成整数。

答案 3 :(得分:5)

这是一个使用NSScanner的简单解决方案(是的,@ NSResponder有一个非常简洁的解决方案!):

NSString *logString = @"user logged (3 attempts)";
NSString *numberString;
NSScanner *scanner = [NSScanner scannerWithString:logString];
[scanner scanUpToCharactersFromSet:[NSCharacterSet decimalDigitCharacterSet] intoString:nil];
[scanner scanCharactersFromSet:[NSCharacterSet decimalDigitCharacterSet] intoString:&numberString];
NSLog(@"Attempts: %i", [numberString intValue]);

NSLog输出:

Attempts: 3

答案 4 :(得分:1)

这是注册用法

NSString *logString = @"user logged (3 attempts)";
NSString * digits = [logString stringByMatching:@"([+\\-]?[0-9]+)" capture:1];