7

有没有一种简单的方法可以将字符串“ dino mcCool ”转换为字符串“ Dino McCool ”?

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

4

2 回答 2

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
于 2013-08-29T20:46:25.917 回答
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:@" "];
}
于 2013-08-29T20:37:52.577 回答