Friday, June 14, 2013

NSCharacterSet lowercaseLetterCharacterSet example in Objective C (iOS).


NSCharacterSet lowercaseLetterCharacterSet

Returns a character set containing the characters in the category of Lowercase Letters.

+ (id)lowercaseLetterCharacterSet

Return Value
A character set containing the characters in the category of Lowercase Letters.

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

NSCharacterSet lowercaseLetterCharacterSet example.
NSCharacterSet *lowerCaseSet = [NSCharacterSet lowercaseLetterCharacterSet];

if ([myString rangeOfCharacterFromSet:lowerCaseSet].location == NSNotFound)
    NSLog(@"String is in upper case.");
else
    NSLog(@"String has invalid characters.");

Example of [NSCharacterSet lowercaseLetterCharacterSet].
NSCharacterSet  *set= [NSCharacterSet alphanumericCharacterSet];
NSString testString = @"This@9";

BOOL bResult = [testString rangeOfCharacterFromSet:[set invertedSet]].location != NSNotFound;
if(bResult)
    NSLog(@"symbol found");

set = [NSCharacterSet uppercaseLetterCharacterSet];
bResult = [password rangeOfCharacterFromSet:set].location != NSNotFound;
if(bResult)
    NSLog(@"upper case latter found");

set = [NSCharacterSet lowercaseLetterCharacterSet];
bResult = [password rangeOfCharacterFromSet:set].location != NSNotFound;
if(bResult)
    NSLog(@"lower case latter found");

set = [NSCharacterSet decimalDigitCharacterSet];
bResult = [password rangeOfCharacterFromSet:set].location != NSNotFound;
if(bResult)
    NSLog(@"digit found");

NSCharacterSet lowercaseLetterCharacterSet example.
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range
replacementString:(NSString *)string {

    // Check if the added string contains lowercase characters.
    // If so, those characters are replaced by uppercase characters.
    // But this has the effect of losing the editing point
    // (only when trying to edit with lowercase characters),
    // because the text of the UITextField is modified.
    // That is why we only replace the text when this is really needed.
    NSRange lowercaseCharRange;
    lowercaseCharRange = [string rangeOfCharacterFromSet:[NSCharacterSet lowercaseLetterCharacterSet]];

    if (lowercaseCharRange.location != NSNotFound) {

        textField.text = [textField.text stringByReplacingCharactersInRange:range
                                                                 withString:[string uppercaseString]];
        return NO;
    }

    return YES;
}

End of NSCharacterSet lowercaseLetterCharacterSet example article.