是否有一种简单的方法可以将字符串“ dino mcCool ”转换为字符串“ Dino McCool ”?
使用“capitalizedString
”方法我会得到@"Dino Mccool"
答案 0 :(得分:16)
您可以枚举字符串的单词并分别修改每个单词。 即使单词由空格字符以外的其他字符分隔,这也有效:
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
答案 1 :(得分:2)
试试这个
- (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:@" "];
}