Monday, May 20, 2013

NSString uppercaseStringWithLocale example ios


[NSString uppercaseStringWithLocale]

Returns uppercased representation of the receiver with the specified locale.
- (NSString *)uppercaseStringWithLocale:(NSLocale *)locale
Parameters
locale
The locale. Passing nil indicates the canonical mapping.
Return Value of [NSString uppercaseStringWithLocale]
An uppercase string using the locale.
Discussion
For the user preference locale setting, pass the result of the NSLocale methodcurrentLocale.
Example of [NSString uppercaseStringWithLocale]
if ([[s uppercaseStringWithLocale:[NSLocale currentLocale]] isEqualToString:s])
{
    // ... s is uppercase ...
}
else
{
    // ... s is not all uppercase ...
}
Example of [NSString uppercaseStringWithLocale]
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    textField.text = [textField.text stringByReplacingCharactersInRange:range
                                                             withString:[string uppercaseStringWithLocale:[NSLocale currentLocale]]];
    return NO;
}
Example of [NSString uppercaseStringWithLocale]
static NSString *CapitalizeSentences(NSString *stringToProcess) {
    NSMutableString *processedString = [stringToProcess mutableCopy];


    NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en"];


    // Ironically, the tokenizer will only tokenize sentences if the first letter
    // of the sentence is capitalized...
    stringToProcess = [stringToProcess uppercaseStringWithLocale:locale];


    CFStringTokenizerRef stringTokenizer = CFStringTokenizerCreate(kCFAllocatorDefault, (__bridge CFStringRef)(stringToProcess), CFRangeMake(0, [stringToProcess length]), kCFStringTokenizerUnitSentence, (__bridge CFLocaleRef)(locale));


    while (CFStringTokenizerAdvanceToNextToken(stringTokenizer) != kCFStringTokenizerTokenNone) {
        CFRange sentenceRange = CFStringTokenizerGetCurrentTokenRange(stringTokenizer);

        if (sentenceRange.location != kCFNotFound && sentenceRange.length > 0) {
            NSRange firstLetterRange = NSMakeRange(sentenceRange.location, 1);

            NSString *uppercaseFirstLetter = [[processedString substringWithRange:firstLetterRange] uppercaseStringWithLocale:locale];

            [processedString replaceCharactersInRange:firstLetterRange withString:uppercaseFirstLetter];
        }
    }


    CFRelease(stringTokenizer);


    return processedString;
}