简体   繁体   中英

Swift apply .uppercaseString to only the first letter of a string

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?

Thanks for any help!

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() + self.lowercased().dropFirst()
    }

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

Swift 5.1 or later

extension StringProtocol {
    var firstUppercased: String { prefix(1).uppercased() + dropFirst() }
    var firstCapitalized: String { prefix(1).capitalized + dropFirst() }
}

Swift 5

extension StringProtocol {
    var firstUppercased: String { return prefix(1).uppercased() + dropFirst() }
    var firstCapitalized: String { return prefix(1).capitalized + dropFirst() }
}

"Swift".first  // "S"
"Swift".last   // "t"
"hello world!!!".firstUppercased  // "Hello world!!!"

"DŽ".firstCapitalized   // "Dž"
"Dž".firstCapitalized   // "Dž"
"dž".firstCapitalized   // "Dž"

Swift 3.0

for "Hello World"

nameOfString.capitalized

or for "HELLO WORLD"

nameOfString.uppercased

Swift 4.0

string.capitalized(with: nil)

or

string.capitalized

However this capitalizes first letter of every word

Apple's documentation:

A capitalized string is a string with the first character in each word changed to its corresponding uppercase value, and all remaining characters set to their corresponding lowercase values. A “word” is any sequence of characters delimited by spaces, tabs, or line terminators. Some common word delimiting punctuation isn't considered, so this property may not generally produce the desired results for multiword strings. See the getLineStart(_:end:contentsEnd:for:) method for additional information.

extension String {
    func firstCharacterUpperCase() -> String? {
        let lowercaseString = self.lowercaseString

        return lowercaseString.stringByReplacingCharactersInRange(lowercaseString.startIndex...lowercaseString.startIndex, withString: String(lowercaseString[lowercaseString.startIndex]).uppercaseString)
    }
}

let x = "heLLo"
let m = x.firstCharacterUpperCase()

For Swift 5:

extension String {
    func firstCharacterUpperCase() -> String? {
        guard !isEmpty else { return nil }
        let lowerCasedString = self.lowercased()
        return lowerCasedString.replacingCharacters(in: lowerCasedString.startIndex...lowerCasedString.startIndex, with: String(lowerCasedString[lowerCasedString.startIndex]).uppercased())
    }
}

单词中的第一个字符使用.capitalized in swift 和整个单词使用.uppercased()

Swift 2.0(单行):

String(nameOfString.characters.prefix(1)).uppercaseString + String(nameOfString.characters.dropFirst())

Swift 3 (xcode 8.3.3)

Uppercase all first characters of string

let str = "your string"
let capStr = str.capitalized

//Your String

Uppercase all characters

let str = "your string"
let upStr = str.uppercased()

//YOUR STRING

Uppercase only first character of string

 var str = "your string"
 let capStr = String(str.characters.prefix(1)).uppercased() + String(str.characters.dropFirst())

//Your string

In swift 5

https://www.hackingwithswift.com/example-code/strings/how-to-capitalize-the-first-letter-of-a-string

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

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

use with your string

let test = "the rain in Spain"
print(test.capitalizingFirstLetter())

Here's a version for Swift 5 that uses the Unicode scalar properties API to bail out if the first letter is already uppercase, or doesn't have a notion of case:

extension String {
  func firstLetterUppercased() -> String {
    guard let first = first, first.isLowercase else { return self }
    return String(first).uppercased() + dropFirst()
  }
}

从 Swift 3 开始,您可以轻松使用textField.autocapitalizationType = UITextAutocapitalizationType.sentences

I'm getting the first character duplicated with Kirsteins' solution. This will capitalise the first character, without seeing double:

var s: String = "hello world"
s = prefix(s, 1).capitalizedString + suffix(s, countElements(s) - 1)

I don't know whether it's more or less efficient, I just know that it gives me the desired result.

In Swift 3.0 (this is a little bit faster and safer than the accepted answer) :

extension String {
    func firstCharacterUpperCase() -> String {
        if let firstCharacter = characters.first {
            return replacingCharacters(in: startIndex..<index(after: startIndex), with: String(firstCharacter).uppercased())
        }
        return ""
    }
}

nameOfString.capitalized won't work , it will capitalize every words in the sentence

Capitalize the first character in the string

extension String {
    var capitalizeFirst: String {
        if self.characters.count == 0 {
            return self

        return String(self[self.startIndex]).capitalized + String(self.characters.dropFirst())
    }
}

Credits to Leonardo Savio Dabus:

I imagine most use cases is to get Proper Casing:

import Foundation

extension String {

    var toProper:String {
        var result = lowercaseString
        result.replaceRange(startIndex...startIndex, with: String(self[startIndex]).capitalizedString)
        return result
    }
}

My solution:

func firstCharacterUppercaseString(string: String) -> String {
    var str = string as NSString
    let firstUppercaseCharacter = str.substringToIndex(1).uppercaseString
    let firstUppercaseCharacterString = str.stringByReplacingCharactersInRange(NSMakeRange(0, 1), withString: firstUppercaseCharacter)
    return firstUppercaseCharacterString
}

Incorporating the answers above, I wrote a small extension that capitalizes the first letter of every word (because that's what I was looking for and figured someone else could use it).

I humbly submit:

extension String {
    var wordCaps:String {
        let listOfWords:[String] = self.componentsSeparatedByString(" ")
        var returnString: String = ""
        for word in listOfWords {
            if word != "" {
                var capWord = word.lowercaseString as String
                capWord.replaceRange(startIndex...startIndex, with: String(capWord[capWord.startIndex]).uppercaseString)
                returnString = returnString + capWord + " "
            }
        }
        if returnString.hasSuffix(" ") {
            returnString.removeAtIndex(returnString.endIndex.predecessor())
        }
        return returnString
    }
}

Swift 4

func firstCharacterUpperCase() -> String {
        if self.count == 0 { return self }
        return prefix(1).uppercased() + dropFirst().lowercased()
    }

Here's the way I did it in small steps, its similar to @Kirsteins.

func capitalizedPhrase(phrase:String) -> String {
    let firstCharIndex = advance(phrase.startIndex, 1)
    let firstChar = phrase.substringToIndex(firstCharIndex).uppercaseString
    let firstCharRange = phrase.startIndex..<firstCharIndex
    return phrase.stringByReplacingCharactersInRange(firstCharRange, withString: firstChar)
}
func helperCapitalizeFirstLetter(stringToBeCapd:String)->String{
    let capString = stringToBeCapd.substringFromIndex(stringToBeCapd.startIndex).capitalizedString
    return capString
}

Also works just pass your string in and get a capitalized one back.

Swift 3 Update

The replaceRange func is now replaceSubrange

nameOfString.replaceSubrange(nameOfString.startIndex...nameOfString.startIndex, with: String(nameOfString[nameOfString.startIndex]).capitalized)

I'm partial to this version, which is a cleaned up version from another answer:

extension String {
  var capitalizedFirst: String {
    let characters = self.characters
    if let first = characters.first {
      return String(first).uppercased() + 
             String(characters.dropFirst())
    }
    return self
  }
}

It strives to be more efficient by only evaluating self.characters once, and then uses consistent forms to create the sub-strings.

Swift 4 (Xcode 9.1)

extension String {
    var capEachWord: String {
        return self.split(separator: " ").map { word in
            return String([word.startIndex]).uppercased() + word.lowercased().dropFirst()
        }.joined(separator: " ")
    }
}

If you want to capitalised each word of string you can use this extension

Swift 4 Xcode 9.2

extension String {
    var wordUppercased: String {
        var aryOfWord = self.split(separator: " ")
        aryOfWord =  aryOfWord.map({String($0.first!).uppercased() + $0.dropFirst()})
        return aryOfWord.joined(separator: " ")
    }
}

Used

print("simple text example".wordUppercased) //output:: "Simple Text Example"

If your string is all caps then below method will work

labelTitle.text = remarks?.lowercased().firstUppercased

This extension will helps you

extension StringProtocol {
    var firstUppercased: String {
        guard let first = first else { return "" }
        return String(first).uppercased() + dropFirst()
    }
}

I'm assuming that you'd like to capitalise the first word of an entire string of words. For example : "my cat is fat, and my fat is flabby" should return "My Cat Is Fat, And My Fat Is Flabby".

Swift 5 :

To do this, you can import Foundation and then use the capitalized property. Example :

import Foundation
var x = "my cat is fat, and my fat is flabby"
print(x.capitalized)  //prints "My Cat Is Fat, And My Fat Is Flabby"

If you want to be a purist and NOT import Foundation , then you can create a String extension.

extension String {
    func capitalize() -> String {
        let arr = self.split(separator: " ").map{String($0)}
        var result = [String]()
        for element in arr {
            result.append(String(element.uppercased().first ?? " ") + element.suffix(element.count-1))
        }
        return result.joined(separator: " ")
    }
}

Then you can use this, like so :

var x = "my cat is fat, and my fat is flabby"
print(x.capitalize()) //prints "My Cat Is Fat, And My Fat Is Flabby"

All in lower case.lowercase()

For first letter upper & other lower.capitalized

All in upper case.uppercased()

extension String {
    var lowercased:String {
        var result = Array<Character>(self.characters);
        if let first = result.first { result[0] = Character(String(first).uppercaseString) }
        return String(result)
    }
}

在 viewDidLoad() 方法中添加这一行。

 txtFieldName.autocapitalizationType = UITextAutocapitalizationType.words

Edit: This no longer works with Text, only supports input fields now.

Just in case someone ends here with the same question regarding SwiftUI:

// Mystring is here
TextField("mystring is here")
   .autocapitalization(.sentences)


// Mystring Is Here
Text("mystring is here")
   .autocapitalization(.words)

For swift 5, you can simple do like that:

Create extension for String:

extension String {
    var firstUppercased: String {
        let firstChar = self.first?.uppercased() ?? ""
        return firstChar + self.dropFirst()
    }
}

then

yourString.firstUppercased

Sample: "abc" -> "Abc"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM