Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ObjC / iOS - Capitalize first letters of each word without modifying other letters

Is there an easy way to transform a string "dino mcCool" to a string "Dino McCool"?

using the 'capitalizedString' method I would just get @"Dino Mccool"

like image 434
budiDino Avatar asked Aug 29 '13 20:08

budiDino


2 Answers

You can enumerate the words of the string and modify each word separately. This works even if the words are separated by other characters than a space character:

NSString *str = @"dino mcCool. foo-bAR";
NSMutableString *result = [str mutableCopy];
[result enumerateSubstringsInRange:NSMakeRange(0, [result length])
                           options:NSStringEnumerationByWords
                        usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
        [result replaceCharactersInRange:NSMakeRange(substringRange.location, 1)
                              withString:[[substring substringToIndex:1] uppercaseString]];
}];
NSLog(@"%@", result);
// Output: Dino McCool. Foo-BAR
like image 116
Martin R Avatar answered Nov 04 '22 03:11

Martin R


Try this

- (NSString *)capitilizeEachWord:(NSString *)sentence {
    NSArray *words = [sentence componentsSeparatedByString:@" "];
    NSMutableArray *newWords = [NSMutableArray array];
    for (NSString *word in words) {
        if (word.length > 0) {
            NSString *capitilizedWord = [[[word substringToIndex:1] uppercaseString] stringByAppendingString:[word substringFromIndex:1]];
            [newWords addObject:capitilizedWord];
        }
    }
    return [newWords componentsJoinedByString:@" "];
}
like image 45
NeverBe Avatar answered Nov 04 '22 02:11

NeverBe