将全部大写的字符串转换为仅包含每个单词大写字母的首字母

时间:2017-11-09 15:51:45

标签: swift string

我从服务器获取字符串,如:

" HELLO WORLD"

但我试图制作的是每个单词都是自己的封面,如:

" Hello World"

我试过这个:

extension String {
    func capitalizingFirstLetter() -> String {
        let first = String(characters.prefix(1)).capitalized
        let other = String(characters.dropFirst()).lowercased()
        return first + other
    }

    mutating func capitalizeFirstLetter() {
        self = self.capitalizingFirstLetter()
    }
}

但结果是

" Hello world"

关于如何做到这一点的任何想法?

1 个答案:

答案 0 :(得分:1)

Apple已经为您做到了这一点:

print("HELLO WORLD".capitalized)

文档:https://developer.apple.com/documentation/foundation/nsstring/1416784-capitalized