Friday, June 14, 2013

NSCharacterSet uppercaseLetterCharacterSet example in Objective C (iOS).


NSCharacterSet uppercaseLetterCharacterSet

Returns a character set containing the characters in the categories of Uppercase Letters and Titlecase Letters.

+ (id)uppercaseLetterCharacterSet

Return Value
A character set containing the characters in the categories of Uppercase Letters and Titlecase Letters.

Discussion of [NSCharacterSet uppercaseLetterCharacterSet]
Informally, this set is the set of all characters used as uppercase letters in alphabets that make case distinctions.

NSCharacterSet uppercaseLetterCharacterSet example.
NSString *s = @"This is a string"; 
int count=0; 
for (i = 0; i < [s length]; i++) {
    BOOL isUppercase = [[NSCharacterSet uppercaseLetterCharacterSet] characterIsMember:[s characterAtIndex:i]];
    if (isUppercase == YES)
       count++;
}

Example of [NSCharacterSet uppercaseLetterCharacterSet].
NSCharacterSet* uppercaseCharSet = [NSCharacterSet uppercaseLetterCharacterSet];
if ([theString rangeOfCharacterFromSet:uppercaseCharSet].location == NSNotFound)
  return NO;

NSCharacterSet* lowercaseCharSet = [NSCharacterSet lowercaseLetterCharacterSet];
if ([theString rangeOfCharacterFromSet:lowercaseCharSet].location == NSNotFound)
  return NO;

NSCharacterSet* digitsCharSet = [NSCharacterSet decimalDigitCharacterSet];
if ([theString rangeOfCharacterFromSet:digitsCharSet].location == NSNotFound)
  return NO;

return YES;
This method is Unicode-aware. If by "Upper case charecter" you just mean A-Z, use

NSCharacterSet* uppercaseCharSet =
    [NSCharacterSet characterSetWithRange:NSMakeRange('A', 26)];

NSCharacterSet uppercaseLetterCharacterSet example.
- (NSArray *)rangesOfUppercaseLettersInString:(NSString *)str {
    NSCharacterSet *cs = [NSCharacterSet uppercaseLetterCharacterSet];
    NSMutableArray *results = [NSMutableArray array];
    NSScanner *scanner = [NSScanner scannerWithString:str];
    while (![scanner isAtEnd]) {
        [scanner scanUpToCharactersFromSet:cs intoString:NULL]; // skip non-uppercase characters
        NSString *temp;
        NSUInteger location = [scanner scanLocation];
        if ([scanner scanCharactersFromSet:cs intoString:&temp]) {
            // found one (or more) uppercase characters
            NSRange range = NSMakeRange(location, [temp length]);
            [results addObject:[NSValue valueWithRange:range]];
        }
    }
    return results;
}

End of NSCharacterSet uppercaseLetterCharacterSet example article.