- 判断是否为整形
+ (BOOL)isInt:(NSString *)str {
NSInteger intStr = 0;
NSScanner *scan = [NSScanner scannerWithString:str];
return [scan scanInteger:&intStr] && [scan isAtEnd];
}
- 判断是否为浮点型
+ (BOOL)isFloat:(NSString *)str {
float floatStr = 0.0;
NSScanner *scan = [NSScanner scannerWithString:str];
return [scan scanFloat:&floatStr] && [scan isAtEnd];
}
- 判断是否为double双精度型
+ (BOOL)isHexInt:(NSString *)str {
unsigned uIntStr = 0;
NSScanner *scan = [NSScanner scannerWithString:str];
return [scan scanHexInt:&uIntStr] && [scan isAtEnd];
}
以字符串
“132 panda lxl of apple”
为例,在扫描完一个整数之后,scanner
的位置将变成3,也即是数字后面的空格处。scanner在任何操作时会跳过空白字符之后才开始,当它找到一个可以扫描的字符时,它会用全部字符去和指定内容匹配,scanner默认情况下会忽略空白字符和换行符。查找字符串
separateString
为"of"
很重要,scanner默认会忽略空白字符,因此数字132后面的空格会被忽略。但是当scanner从空格后面的字符开始扫描时,所有的字符都会被加载到输出字符串中,一直到遇到搜索字符串"of"。注意:如果搜索字符串是“of”,(前面没空格),name的值应该是"fushipingguo "(最后面有个空格);如果搜索字符串是" of",(前面有空格),则name的值为"fushi pingguo"(最后面无空格)。在扫描到指定字符串(搜索字符串)后,scanner的位置指向了该字符串的开始处。此时,如果我们想继续扫描该字符串之后的字符,则同上面一样,必须先扫描指定字符串(搜索字符串)
+ (void)suosuoStr {
NSString *apple = @"132 fushi pingguo of apple";
//注意of前面有一个空格
NSString *separateString = @" of";
NSScanner *aScanner = [NSScanner scannerWithString:apple];
NSInteger anInteger;
//得到数量132
[aScanner scanInteger:&anInteger];
NSLog(@"%ld", (long)anInteger);
NSString *name;
//得到名称fushi pingguo
[aScanner scanUpToString:separateString intoString:&name];
NSLog(@"%@", name);
}
//截取字符串中的数字
+ (void)suosuoInt {
NSString *str = @"Product:Lxl Panda Peter;Cost:0.23 87\n\Product:Xiong Mao Bet;Cost:0.38 76\n\Product:San Di Sex;Cost:1.29 3\n";
NSCharacterSet *semicolonSet;
NSScanner *theScanner;
NSString *PRODUCT =@"Product:";
NSString *COST = @"Cost:";
NSString *productNmae;
float productCost;
NSInteger productSold;
semicolonSet = [NSCharacterSet characterSetWithCharactersInString:@";"];
theScanner = [NSScanner scannerWithString:str];
while([theScanner isAtEnd] == NO) {
if([theScanner scanString:PRODUCT intoString:NULL] &&
[theScanner scanUpToCharactersFromSet:semicolonSet intoString:&productNmae] &&
[theScanner scanString:@";" intoString:NULL] &&
[theScanner scanString:COST intoString:NULL] &&
[theScanner scanFloat:&productCost] &&
[theScanner scanInteger:&productSold]) {
//得到Sales of Lxl Panda Peter:$20.01
//Sales of Xiong Mao Bet:$28.88
//Sales of San Di Sex:$3.87
NSLog(@"Sales of %@:$%1.2f",productNmae,productCost*productSold);
}
}
}