How to use NSScanner?

Zopi picture Zopi · Feb 27, 2009 · Viewed 36.1k times · Source

I've just read Apple documentation for NSScanner. I'm trying to get the integer of this string:

@"user logged (3 attempts)"

I can't find any example, how to scan within parentheses. Any ideas?

Here's the code:

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

[aScanner scanInteger:anInteger];

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

Answer

NSResponder picture NSResponder · Aug 20, 2009

Ziltoid's solution works, but it's more code than you need.

I wouldn't bother instantiating an NSScanner for the given situation. NSCharacterSet and NSString give you all you need:

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

or in Swift:

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