ObjC / iOS – 在不修改其他字母的情况下大写每个单词的首字母

有没有简单的方法将string“ dino mcCool ”转换为string“ Dino McCool ”?

使用' capitalizedString '方法,我只会得到@"Dino Mccool"

您可以枚举string的单词并单独修改每个单词。 即使单词被空格字符以外的其他字符分隔,也是如此:

 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 

尝试这个

 - (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:@" "]; }