William Sidell

Software Developer Entrepreneur

  • HomeAll the news
  • Portfoliovery cool stuff
  • AboutA bit about me
  • ConnectFind me on the grid

April 16, 2011
Posted by William

Objective-C NSString Extracting Numbers

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.

/*
*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;
}

1 Comment

Posted Under Tutorials

1 Comments

--Nick/
April 3, 2012

Thanks, William, for saving me some time.

Leave a comment

* = Required

    • Posts
    • Twitter
    • Flickr
     

    iOS 6 UIPasteboard...

    iOS

     

    Three20 iOS 6...

    iOS

     

    1st Place Startup...

    iOS

    Check out this awesome Photo Mosaic I made using "InstaMosaic" for iPhone http://t.co/b4cYtyDu http://t.co/I9uc7clq

    follow me on
    twitter

    2013.05.25 - _NKN4657.jpgIMG_0948Vivid - inside evolving world of photojournalismIMG_3907
  • Categories

    • Interesting Stuff
    • iOS
    • Tutorials
  • Archives

    • 2012
      • January
      • March
      • September
      • October
    • 2011
      • February
      • March
      • April
      • June
    • 2010
      • October
  • Blogroll

    • Enchanted Cloud Studios

Subscribe via RSS