7

文字列「 dino mcCool」を文字列「Dino McCool 」に変換する簡単な方法はありますか?

capitalizedString' ' メソッドを使用して取得する@"Dino Mccool"

4

2 に答える 2

16

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
于 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 に答える