Note that because a scannerskips whitespace and newlines by default, the loop does no special processing for them (in particular there is no need to do additional whitespace processing to retrieve the final integer).
NSString *string = @"Product: Acme Potato Peeler; Cost: 0.98 73\n\ |
Product: Chef Pierre Pasta Fork; Cost: 0.75 19\n\ |
Product: Chef Pierre Colander; Cost: 1.27 2\n"; |
|
|
NSCharacterSet *semicolonSet; |
NSScanner *theScanner; |
|
|
NSString *PRODUCT = @"Product:"; |
NSString *COST = @"Cost:"; |
|
|
NSString *productName; |
float productCost; |
NSInteger productSold; |
|
|
semicolonSet = [NSCharacterSet characterSetWithCharactersInString:@";"]; |
theScanner = [NSScanner scannerWithString:string]; |
|
|
while ([theScanner isAtEnd] == NO) |
{
|
if ([theScanner scanString:PRODUCT intoString:NULL] && |
[theScanner scanUpToCharactersFromSet:semicolonSet |
intoString:&productName] && |
[theScanner scanString:@";" intoString:NULL] && |
[theScanner scanString:COST intoString:NULL] && |
[theScanner scanFloat:&productCost] && |
[theScanner scanInteger:&productSold]) |
{
|
NSLog(@"Sales of %@: $%1.2f", productName, productCost * productSold); |
} |
} |
2012-08-15 10:10:22.600 TestCoreData[912:c07] Sales of Acme Potato Peeler: $71.54
2012-08-15 10:16:20.469 TestCoreData[912:c07] Sales of Chef Pierre Pasta Fork: $14.25
2012-08-15 10:16:23.102 TestCoreData[912:c07] Sales of Chef Pierre Colander: $2.54
使用NSScanner解析产品销售数据
本文介绍如何利用Objective-C中的NSScanner类来解析包含产品名称和成本的字符串数据,并计算销售总额。通过创建特定字符集并利用NSScanner的方法逐项扫描字符串,可以有效地解析出每个产品的名称及其成本。
1525

被折叠的 条评论
为什么被折叠?



