如何使用 NSScanner?
我刚刚读过 Apple NSScanner
的文档。 我试图获取该字符串的整数:
@"user logged (3 attempts)"
我找不到任何示例,如何在括号内扫描。 有任何想法吗?
这是代码:
NSString *logString = @"user logged (3 attempts)";
NSScanner *aScanner = [NSScanner scannerWithString:logString];
[aScanner scanInteger:anInteger];
NSLog(@"Attempts: %i", anInteger);
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);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
Ziltoid 的解决方案有效,但代码量超出了您的需要。
我不会为给定的情况实例化 NSScanner 。 NSCharacterSet 和 NSString 为您提供所需的一切:
或者在 Swift 中:
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:
or in Swift:
`这是我从字符串中获取某些值的方法,
首先我定义了这个方法
然后调用它。
leftOffset 是左侧字符串的字符数
可能是一种更简单、更清晰的方法,但这是我的解决方案。
`Here is what I do to get certain values out of a string
First I have this method defined
Then call it.
leftOffset is the number of characters for the left string
Could be an easier cleaner way but that was my solution.
这是一个使用 NSScanner 的简单解决方案(是的,@NSResponder 有一个非常简洁的解决方案!):
NSLog 输出:
Here is a simple solution using NSScanner (yes, @NSResponder has a really neat solution!):
NSLog output:
NSScanner
是一个线性扫描仪。 你必须浏览你不想要的东西才能得到你想要的东西。您可以执行
[aScanner scanUpToCharactersInSet:[NSCharacterSet DecimalDigitCharacterSet] intoString:NULL]
跳过所有内容直到数字字符。 然后,您执行[aScanner scanInteger:&anInteger]
将字符扫描为整数。NSScanner
is a linear scanner. You have to scan through the stuff you don't want to get to what you do want.You could do
[aScanner scanUpToCharactersInSet:[NSCharacterSet decimalDigitCharacterSet] intoString:NULL]
to jump past everything up to the number character. Then you do[aScanner scanInteger:&anInteger]
to scan the character into an integer.这是正则表达式的用法
here is the reg-ex usage