iOS Quick Tip: Find a Number from within an NSString

Stephen Zaharuk / Thursday, May 8, 2014

If you have a string representation of a number, NSString has a few helper methods that make it easy to grab a number. But what happens when you have a string made up of letters and numbers, and you just want the number?

First lets look at how you get a number from a string that is just made up of digits:

@"12"

NSString* val = @"12";
NSInteger number = val.integerValue;

@"3.14"

NSString* val = @"3.14";
CGFloat number = val.floatValue;

Now lets see how you can find a number in a more complex string:

@"Find this number: 256"

NSString* val = @"Find this number: 256";
NSString* numberString;

NSScanner *scanner = [NSScanner scannerWithString:val];
NSCharacterSet *numbers = [NSCharacterSet characterSetWithCharactersInString:@"0123456789."];

// Throw away characters before the first number.
[scanner scanUpToCharactersFromSet:numbers intoString:NULL];

// Collect numbers.
[scanner scanCharactersFromSet:numbers intoString:&numberString];
NSInteger number = numberString.integerValue;

Enjoy!

By Stephen Zaharuk (SteveZ)