Swift仅将.uppercaseString应用于字符串的第一个字母 [英] Swift apply .uppercaseString to only the first letter of a string

查看:271
本文介绍了Swift仅将.uppercaseString应用于字符串的第一个字母的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个自动更正系统,当用户键入带有大写字母的单词时,自动更正功能不起作用。为了解决这个问题,我制作了一个字符串类型的副本,应用了.lowercaseString,然后对它们进行了比较。如果字符串确实是错误的,它应该纠正这个词。然而,替换键入的单词的单词都是小写的。所以我需要将.uppercaseString仅应用于第一个字母。我原本以为我可以使用

I am trying to make an autocorrect system, and when a user types a word with a capital letter, the autocorrect doesn't work. In order to fix this, I made a copy of the string typed, applied .lowercaseString, and then compared them. If the string is indeed mistyped, it should correct the word. However then the word that replaces the typed word is all lowercase. So I need to apply .uppercaseString to only the first letter. I originally thought I could use

nameOfString[0]

但这显然不起作用。如何将字符串的第一个字母设置为大写,然后能够打印第一个字母大写的完整字符串?

but this apparently does not work. How can I get the first letter of the string to uppercase, and then be able to print the full string with the first letter capitalized?

感谢您的帮助!

推荐答案

包括变异和非变异与API指南一致的版本。

Including mutating and non mutating versions that are consistent with API guidelines.

Swift 3:

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

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

Swift 4:

extension String {
    func capitalizingFirstLetter() -> String {
      return prefix(1).uppercased() + dropFirst()
    }

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

这篇关于Swift仅将.uppercaseString应用于字符串的第一个字母的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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