ObjC / iOS - 将每个单词的首字母大写,而不修改其他字母 [英] ObjC / iOS - Capitalize first letters of each word without modifying other letters

查看:396
本文介绍了ObjC / iOS - 将每个单词的首字母大写,而不修改其他字母的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种简单的方法可以将字符串 dino mcCool 转换为字符串 Dino McCool

Is there an easy way to transform a string "dino mcCool" to a string "Dino McCool"?

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

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

推荐答案

您可以枚举字符串的单词并分别修改每个单词。
即使单词由空格字符以外的其他字符分隔,这也有效:

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

这篇关于ObjC / iOS - 将每个单词的首字母大写,而不修改其他字母的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆