How to use NSScanner?

前端 未结 5 1595
走了就别回头了
走了就别回头了 2020-11-27 17:40

I\'ve just read Apple\'s docu of NSScanner. I\'m trying to get the integer of that string: @\"user logged (3 attempts)\".

I can\'t find any example, how to scan with

5条回答
  •  猫巷女王i
    2020-11-27 18:14

    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)
    

提交回复
热议问题