Powered By Blogger

Tuesday, October 22, 2013

How can we extract numbers from a string in iPhone?

Hi,

Here is the way to separate numbers from a mixed character string. For this , anybody can use "NSScanner" in their own way. I use this one to filter numbers from the given input string. Please have look ...

For Example : 

NSString *string = @"45#%ds32(())_*x 34";
NSMutableString *newStrStrip = [NSMutableString
        stringWithCapacity:newStrStrip.length];

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

while ([scanner isAtEnd] == NO)
{
  NSString *buffer;
      if ([scanner scanCharactersFromSet:numbers intoString:&buffer])
     {
          [newStrStrip appendString:buffer];
     }
     else
     {
          [scanner setScanLocation:([scanner scanLocation] + 1)];
     }
}

NSLog(@"OUTPUT : %@", newStrStrip);  // "OUTPUT : 453234"


Regards,
Nilesh M. Prajapati