Friday, June 14, 2013

NSCharacterSet decimalDigitCharacterSet example in Objective C (iOS).


NSCharacterSet decimalDigitCharacterSet

Returns a character set containing the characters in the category of Decimal Numbers.

+ (id)decimalDigitCharacterSet

Return Value
A character set containing the characters in the category of Decimal Numbers.

Discussion of [NSCharacterSet decimalDigitCharacterSet]
Informally, this set is the set of all characters used to represent the decimal values 0 through 9. These characters include, for example, the decimal digits of the Indic scripts and Arabic.

NSCharacterSet decimalDigitCharacterSet example.
NSString *newString = [[origString componentsSeparatedByCharactersInSet:
             [[NSCharacterSet decimalDigitCharacterSet] invertedSet]]
             componentsJoinedByString:@""];

Example of [NSCharacterSet decimalDigitCharacterSet].
Here's one way that doesn't rely on the limited precision of attempting to parse the string as a number:

NSCharacterSet* notDigits = [[NSCharacterSet decimalDigitCharacterSet] invertedSet];
if ([newString rangeOfCharacterFromSet:notDigits].location == NSNotFound)
{
    // newString consists only of the digits 0 through 9
}

NSCharacterSet decimalDigitCharacterSet example.
 NSString *str = @"001234852ACDSB";
    NSScanner *scanner = [NSScanner scannerWithString:str];

    // set it to skip non-numeric characters
    [scanner setCharactersToBeSkipped:[[NSCharacterSet decimalDigitCharacterSet] invertedSet]];

    int i;
    while ([scanner scanInt:&i])
    {
        NSLog(@"Found int: %d",i);    //001234852
    }

    // reset the scanner to skip numeric characters
    [scanner setScanLocation:0];
    [scanner setCharactersToBeSkipped:[NSCharacterSet decimalDigitCharacterSet]];

    NSString *resultString;
    while ([scanner scanUpToCharactersFromSet:[NSCharacterSet decimalDigitCharacterSet] intoString:&resultString])
    {
        NSLog(@"Found string: %@",resultString);    //ACDSB
    }

End of NSCharacterSet decimalDigitCharacterSet example article.