I have a string that contains words as well as a number. How can I extract that number from the string?
NSString *str = @"This is my string. #1234";
I would like to be able to strip out 1234 as an int. The string will have different numbers and words each time I search it.
Ideas?
Here's an NSScanner based solution:
(Some of the many) assumptions made here:
int
.Alternatively you could scan direct to the
int
:If the
#
marks the start of the number in the string, you could find it by means of:Try this answer from Stack Overflow for a nice piece of C code that will do the trick:
NSPredicate is the Cocoa class for parsing string using ICU regular expression.
By far the best solution! I think regexp would be better, but i kind of sux at it ;-) this filters ALL numbers and concats them together, making a new string. If you want to split multiple numbers change it a bit. And remember that when you use this inside a big loop it costs performance!
Self contained solution:
Handles the following cases:
Hope this helps!
You could use the NSRegularExpression class, available since iOS SDK 4.
Bellow a simple code to extract integer numbers ("\d+" regex pattern) :