ObjC / iOS - capital letters of each word without changing other letters

Is there an easy way to convert the string " dino mcCool " to the string " Dino McCool "?

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

+7
ios objective-c
source share
2 answers

You can list the words of a string and change each word separately. This works even if words are separated by other characters than the whitespace 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 
+16
source share

try it

 - (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:@" "]; } 
+2
source share

All Articles