- 判斷是否為整形
+ (BOOL)isInt:(NSString *)str {
NSInteger intStr = 0;
NSScanner *scan = [NSScanner scannerWithString:str];
return [scan scanInteger:&intStr] && [scan isAtEnd];
}
- 判斷是否為浮點(diǎn)型
+ (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”
為例粒氧,在掃描完一個(gè)整數(shù)之后,scanner
的位置將變成3根吁,也即是數(shù)字后面的空格處。scanner在任何操作時(shí)會(huì)跳過(guò)空白字符之后才開始,當(dāng)它找到一個(gè)可以掃描的字符時(shí)合呐,它會(huì)用全部字符去和指定內(nèi)容匹配,scanner默認(rèn)情況下會(huì)忽略空白字符和換行符荷并。查找字符串
separateString
為"of"
很重要合砂,scanner默認(rèn)會(huì)忽略空白字符,因此數(shù)字132后面的空格會(huì)被忽略源织。但是當(dāng)scanner從空格后面的字符開始掃描時(shí)翩伪,所有的字符都會(huì)被加載到輸出字符串中,一直到遇到搜索字符串"of"谈息。注意:如果搜索字符串是“of”缘屹,(前面沒(méi)空格),name的值應(yīng)該是"fushipingguo "(最后面有個(gè)空格)侠仇;如果搜索字符串是" of"轻姿,(前面有空格),則name的值為"fushi pingguo"(最后面無(wú)空格)逻炊。在掃描到指定字符串(搜索字符串)后互亮,scanner的位置指向了該字符串的開始處。此時(shí)余素,如果我們想繼續(xù)掃描該字符串之后的字符豹休,則同上面一樣,必須先掃描指定字符串(搜索字符串)
+ (void)suosuoStr {
NSString *apple = @"132 fushi pingguo of apple";
//注意of前面有一個(gè)空格
NSString *separateString = @" of";
NSScanner *aScanner = [NSScanner scannerWithString:apple];
NSInteger anInteger;
//得到數(shù)量132
[aScanner scanInteger:&anInteger];
NSLog(@"%ld", (long)anInteger);
NSString *name;
//得到名稱fushi pingguo
[aScanner scanUpToString:separateString intoString:&name];
NSLog(@"%@", name);
}
//截取字符串中的數(shù)字
+ (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);
}
}
}