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