Powered By Blogger
Showing posts with label NSScanner. Show all posts
Showing posts with label NSScanner. Show all posts

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

Monday, April 2, 2012

UIColor using HexCode

Here is the useful method for retrieving UIColor using the HexCode in your application. So, you can use your customize colors in application development.


- (UIColor *)colorWithHexCode:(NSString *)strHexCode
{
     NSString *cString = [[strHexCode stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
   
     // String should be 6 or 8 characters
     if ([cString length] < 6) return [UIColor grayColor];
   
     // strip 0X if it appears
     if ([cString hasPrefix:@"#"]) cString = [cString substringFromIndex:1];
   
     if ([cString length] != 6) return [UIColor grayColor];
   
     // Separate into r, g, b substrings
     NSRange range;
     range.location = 0;
     range.length = 2;
     NSString *rString = [cString substringWithRange:range];
   
     range.location = 2;
     NSString *gString = [cString substringWithRange:range];
   
     range.location = 4;
     NSString *bString = [cString substringWithRange:range];
   
     // Scan values
     unsigned int red, green, blue;
     [[NSScanner scannerWithString:rString] scanHexInt:&red];
     [[NSScanner scannerWithString:gString] scanHexInt:&green];
     [[NSScanner scannerWithString:bString] scanHexInt:&blue];
   
     return [UIColor colorWithRed:(red / 255.0f)
                      green:(green / 255.0f)
                       blue:(blue / 255.0f)
                      alpha:1.0f];
}




Thanks and Regards,
Nilesh Prajapati