On one of the projects that I was working on recently, I needed to be able to pull out all the numbers from the string. Here is the method that I wrote if anyone wants to use it. It is based off some code from stack overflow but is changed to work for more than one number.
[cce]
/*
*Takes string input and returns NSArray of NSNumbers
*/
+(NSArray *) extractNumbersFromString:(NSString *)string {
NSMutableArray *numbers = [[NSMutableArray alloc] init];
NSString *numberString;
NSScanner *scanner = [NSScanner scannerWithString:string];
NSCharacterSet *filter = [NSCharacterSet characterSetWithCharactersInString:@”0123456789″];
while ([scanner isAtEnd] == NO) {
numberString = @””;
[scanner scanUpToCharactersFromSet:filter intoString:NULL];
if ([scanner scanCharactersFromSet:filter intoString:&;numberString]) {
[numbers addObject:[NSNumber numberWithInt:[numberString intValue]]];
}
}
NSArray *array = [[[NSArray alloc] initWithArray:numbers] autorelease];
[numbers release];
return array;
}
[/cce]
Thanks, William, for saving me some time.
Heck yeah this is extlacy what I needed.