254
votes

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!

30
the accepted answer is no longer valid, please check this oneJuan Boero

30 Answers

547
votes

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()
    }
}
174
votes

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ž"
101
votes

Swift 3.0

for "Hello World"

nameOfString.capitalized

or for "HELLO WORLD"

nameOfString.uppercased
47
votes

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.

24
votes
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())
    }
}
19
votes

For first character in word use .capitalized in swift and for whole-word use .uppercased()

10
votes

Swift 2.0 (Single line):

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

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
5
votes

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())
4
votes

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()
  }
}
3
votes

From Swift 3 you can easily use textField.autocapitalizationType = UITextAutocapitalizationType.sentences

2
votes

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.

2
votes

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())
    }
}
2
votes

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

1
votes

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
    }
}
1
votes

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
}
1
votes

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
    }
}
1
votes

Swift 4

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

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)
}
0
votes
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.

0
votes

Swift 3 Update

The replaceRange func is now replaceSubrange

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

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.

0
votes

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: " ")
    }
}
0
votes

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"
0
votes

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()
    }
}
0
votes

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

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


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

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"
-1
votes
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)
    }
}
-1
votes

Add this line in viewDidLoad() method.

 txtFieldName.autocapitalizationType = UITextAutocapitalizationType.words
-3
votes

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"