swift - 将全部大写的字符串转换为只有每个单词大写的首字母

标签 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 ”

知道怎么做吗?

最佳答案

Apple 已经为您做到了:

print("HELLO WORLD".capitalized)

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

关于swift - 将全部大写的字符串转换为只有每个单词大写的首字母,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47206158/

相关文章:

ios - 如何增加 UITableView 中自定义单元格的宽度

ios - 从 com.apple.main-thread 入队(线程 1)崩溃 | iOS | swift 4.1

ios - 带有 iOS swift 的 Facebook SDK 无法在 UIWebView 中打开

ios - 单元格不显示

java - 替换字符并仅保留其中一个字符

java - 从字符列表中创建字符串然后清除它的最有效方法

c++ - 使用 getline 函数获取段错误?

ios - 使用 swift 客户端库时服务器 Socket.io 回调崩溃

python - 使用数据框的名称作为字符串

string - 在Elasticsearch中对关键字查询的句子