@luckyJerry
2015-09-23T05:30:50.000000Z
字数 1087
阅读 443
iOS
NSScaner API
NSScaner Reference
NSScaner从名字上看,我还以为是扫描仪之类的抽象。其实,这个类是用来处理字符串的。可以扫描字符串中自己想要的信息。可以从字符串中抽取出int,long,double之类的数据。也可以用来截取一部分的字符串。
需要解释一下NSScaner中的一个重要的概念scanLocation,这个属性指明了从哪个位置开始扫描。每次扫描到想要的内容后,scanLocation会移动到该内容后面的位置上。比如:扫描“137 small cases of bananas”这个字符串的int内容之后, scanLocation就是3。
创建Scaner的时候,有一个需要扫描的NSString作为参数。
+ scannerWithString:+ localizedScannerWithString:- initWithString:
想要在Scaner中寻找数字是一件很方便的事,Scaner提供了一连串的方法。
- scanDecimal:- scanDouble:- scanFloat:- scanHexDouble:- scanHexFloat:- scanHexInt:- scanHexLongLong:- scanInteger:- scanInt:- scanLongLong:- scanUnsignedLongLong:
另外还可以寻找字符串
- scanString:intoString:- scanUpToString:intoString:
什么,你问有啥区别?举个栗子:
NSString *originalString = @"137 small cases of bananas";NSScaner *scaner = [NSScaner alloc] initWithString:originalString】;NSString *seperator = @"of";NSString *result = nil;[scaner scanUpToString:seperator intoString:&result];NSlog(@"%@", result); //@"137 small cases "[scaner scanString:seperator intoString:&result];NSlog(@"%@", result); //@"of"
第二个参数代入nil的话,可以用来跳过字符串的某些部分。
[scaner scanUpToString:seperator intoString:nil];
这样可以让scanLocation移到seperator的后面