279

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!

Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
SomeGuy
  • 3,725
  • 3
  • 19
  • 23
  • 1
    the accepted answer is no longer valid, please check [this one](https://stackoverflow.com/a/40933056/1634890) – Juan Boero Mar 11 '21 at 20:01

31 Answers31

567

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()
    }
}
Fahim Parkar
  • 30,974
  • 45
  • 160
  • 276
Kirsteins
  • 27,065
  • 8
  • 76
  • 78
  • note that this capitalizes the first letter of every word – newacct Oct 11 '14 at 02:14
  • 3
    Just a note that `.capitalizedString` no longer works in Xcode 7 Beta 4. Strings have changed a bit in Swift 2.0. – kakubei Jul 27 '15 at 10:20
  • 2
    @Kirsteins: you're right, my bad. I'd forgotten to import `Foundation` *sheepish grin* – kakubei Jul 28 '15 at 15:55
  • 3
    @LoryLory Use `.uppercaseString` for that – Kirsteins Sep 08 '15 at 16:58
  • If you're looking for something similar to Rails titleize, see http://dev.iachieved.it/iachievedit/swift-titleized-string-extension/ (disclaimer: I'm the author) – Joe Sep 19 '15 at 23:55
  • 2
    This is the seriously effective answer mate..Working with Xcode 7.1.1/ Swift 2.1....Thanks :) – onCompletion Dec 08 '15 at 13:08
  • i have imported the "Foundation" and tried both function.but both are not working.XCode version is 7.3 – Chandramani Aug 17 '16 at 11:03
  • @cmp Can you post full example. What error are you getting? – Kirsteins Aug 17 '16 at 11:04
  • 1
    You might want to add `.lowercaseString` to `String(characters.dropFirst())` as if the user passes an uppercase string it will remain entirely uppercase. Of course this also means that you need to watch out for instances where proper nouns etc require capital letters... – Ash Sep 20 '16 at 11:07
  • FYI: the Swift 3 solution only works on the first character of any string, not the first character of every sentence, so it's kinda useless. Does not capitalize the first word of every sentence like I thought it was. – Hedylove Oct 14 '16 at 03:55
  • 32
    its just `.capitalized` now. Note also `capitalizedStringWith(_ locale:)` – Raphael Mar 07 '17 at 10:12
  • 1
    added `self.lowercased().` if the actual string is upper cased and need title case for this word... So "WORLD" will be "World" with above change... – Fahim Parkar Oct 25 '18 at 11:33
209

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ž"
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
  • 3
    Nice job. I edited mine to pass lowercase first and renamed to Proper. – ericgu Mar 02 '15 at 19:12
  • I like the swift 2.1.1 solution, but when I run my app and check for leaks, it's showing this is leaking. – Henny Lee Jan 09 '16 at 17:07
  • 1
    I just created a new project and it seems it causes a memory leak when this is used together with a `UITextField` observer for `UITextFieldTextDidChangeNotification`. – Henny Lee Jan 09 '16 at 19:35
  • @Henry this has nothing to do with the code itself. if you experience any performance/memory issue you should report it to Apple. – Leo Dabus Jan 09 '16 at 19:51
  • Works only if the strings was lowercased from the start. – Teodor Ciuraru Jan 21 '17 at 11:11
  • Should be: "var uppercaseFirst: String { return first.uppercased() + String(characters.dropFirst()).--->lowercased<--- }" to ensure camel case with everything lower case after – mskw Aug 15 '17 at 20:30
  • @mskw for that you can use String property capitalized. `"ABC".capitalized`. If you want it all lowercased `"ABC DEF".lowercased().uppercaseFirst` – Leo Dabus Aug 15 '17 at 20:42
  • Re `else { return “” }`: Wouldn’t `else { return self }` also work? No first character means `self` is already the empty string, right? – Nicolas Miari Sep 21 '17 at 23:58
  • @NicolasMiari Yes if there is no first character returning self would also return an empty string – Leo Dabus Sep 21 '17 at 23:59
  • 1
    @LeoDabus I guess it’s down to Which one makes the code’s intent more evident. Empty string literal is perhaps best. – Nicolas Miari Sep 22 '17 at 00:02
  • Completely totally wrong. Turning the first character to uppercase is not the same as capitalising. There are letters like DŽ Dž and dž that come in uppercase, capitalised and lowercase form. Your code would incorrectly use the uppercase form. – gnasher729 Aug 05 '18 at 11:18
  • It does what OP asked it uppercases only the first letter – Leo Dabus Aug 05 '18 at 11:40
  • What if all the characters are capital in input string? Will `dropfirst()` work? – Hamza Hasan May 21 '20 at 23:44
  • @HamzaHasan Well if the first character it is already uppercased nothing will happen. If you need to capitalize each work there is already a String property called capitalized. If your intent is to have the whole string other than the first letter lowercased you need to call `string.lowercased().firstCapitalized`. – Leo Dabus May 22 '20 at 00:13
116

Swift 3.0

for "Hello World"

nameOfString.capitalized

or for "HELLO WORLD"

nameOfString.uppercased
Maselko
  • 4,028
  • 2
  • 22
  • 21
  • 3
    Charlesism has already answered with the Swift 3 version two months ago... – Eric Aya Dec 02 '16 at 13:22
  • 17
    This will capitalize the first character of every word of the String and not just the first word. – Bocaxica Mar 08 '17 at 17:23
  • Returns: An uppercase copy of the string. public func uppercased() -> String Swift 3.0 or for "HELLO WORLD" nameOfString.uppercased INSTEAD OF ABOVE nameOfString.uppercased() – Azharhussain Shaikh Jun 06 '17 at 07:26
54

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.

sam k
  • 1,048
  • 2
  • 14
  • 22
  • 3
    I have no idea why people aren't receptive to this answer. If people want just the first word capitalized they can grab out the first and capitalize it most easily with the capitalized property. – ScottyBlades Dec 10 '17 at 21:03
  • 2
    Importantly, "Capitalised" is correct for all Unicode characters, while using "uppercased" for the first character isn't. – gnasher729 Aug 05 '18 at 11:20
27
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())
    }
}
James Rochabrun
  • 4,137
  • 2
  • 20
  • 17
user2260304
  • 319
  • 5
  • 6
  • This is the best answer IMO - keeps it simple for all future cases. – Robert Jan 05 '16 at 02:20
  • No need to check if string `isEmpty` and initialize a string to replace either. You can simply unwrap the first character and in case it fails just return nil. This can be simplified as `var firstCharacterUpperCase: String? { guard let first = first else { return nil } return lowercased().replacingCharacters(in: startIndex...startIndex, with: first.uppercased()) }` – Leo Dabus May 22 '20 at 00:28
27

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

mxcl
  • 26,392
  • 12
  • 99
  • 98
DURGESH
  • 2,373
  • 1
  • 15
  • 13
10

Swift 2.0 (Single line):

String(nameOfString.characters.prefix(1)).uppercaseString + String(nameOfString.characters.dropFirst())
Phil
  • 4,730
  • 1
  • 41
  • 39
  • 1
    Upvoted. However, this assumes that the original string is all lower case. I added `.localizedLowercaseString` at the end to make it work with strings like: aNYsTring. `String(nameOfString.characters.prefix(1)).uppercaseString + String(nameOfString.characters.dropFirst()).localizedLowercaseString` – oyalhi Sep 06 '16 at 17:45
10

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())
Pranav Kasetti
  • 8,770
  • 2
  • 50
  • 71
Sanjay Mishra
  • 672
  • 7
  • 17
6

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
oscar castellon
  • 3,048
  • 30
  • 19
4

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()
  }
}
Adam Sharp
  • 3,618
  • 25
  • 29
  • No need to initialize a String with the first character. `return first.uppercased() + dropFirst()` or one liner `(first?.uppercased() ?? "") + dropFirst()` – Leo Dabus May 22 '20 at 00:32
4

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"
vnerurkar
  • 41
  • 3
  • This fixed my problem because I wanted to make 'ExamPLE' from 'examPLE', built-in capitalized property returns the word capitalized but it also lowercase all other letters in the word, like this 'Example' which was not working for me. Thanks @vnerurkar – Boris Nikolic May 06 '22 at 12:02
3

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

Yura
  • 262
  • 2
  • 11
2

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.

Marc Fearby
  • 1,305
  • 1
  • 13
  • 28
  • You could test whether capitalizing the first character changes that character - by saving it in its own constant then testing equality with the new 'capitalized' string, and if they are the same then you already have what you want. – David H Apr 23 '15 at 13:14
  • Your post inspired this answer - thanks!: func capitaizeFirstChar(var s: String) -> String { if s.isEmpty == false { let range = s.startIndex...s.startIndex let original = s.substringWithRange(range) let capitalized = original.capitalizedString if original == capitalized { return s } s.replaceRange(range, with: capitalized) } return s } – David H Apr 23 '15 at 13:43
  • 1
    In newer versions of Swift, `countElements` is just `count`. – George Poulos Jul 16 '15 at 22:25
2

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

aehlke
  • 15,225
  • 5
  • 36
  • 45
pierre23
  • 3,846
  • 1
  • 28
  • 28
2

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())
    }
}
Tziki
  • 311
  • 1
  • 8
1

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
    }
}
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
ericgu
  • 2,229
  • 23
  • 25
1

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
}
Nazariy Vlizlo
  • 778
  • 7
  • 16
1

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"
Shilpriya
  • 93
  • 6
1

Swift 4

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

All in lower case .lowercase()

For first letter upper & other lower .capitalized

All in upper case .uppercased()

Tipu
  • 19
  • 4
0

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)
}
abc123
  • 8,043
  • 7
  • 49
  • 80
0

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
    }
}
Matt
  • 2,576
  • 6
  • 34
  • 52
  • 2
    Swift String has a method called capitalizedString. If you need to apply it to an array of strings check this answer http://stackoverflow.com/a/28690655/2303865 – Leo Dabus Feb 17 '16 at 19:59
  • The question is asking for sentence case and this answer may not respect other languages—best to use the existing `capitalizedString`. – Warpling Nov 22 '21 at 13:02
0
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.

Dan Leonard
  • 3,325
  • 1
  • 20
  • 32
0

Swift 3 Update

The replaceRange func is now replaceSubrange

nameOfString.replaceSubrange(nameOfString.startIndex...nameOfString.startIndex, with: String(nameOfString[nameOfString.startIndex]).capitalized)
Rool Paap
  • 1,918
  • 4
  • 32
  • 39
0

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.

Patrick Beard
  • 592
  • 6
  • 11
0

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: " ")
    }
}
Daniel R
  • 312
  • 1
  • 9
0

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()
    }
}
Ashu
  • 3,373
  • 38
  • 34
  • 1
    simply use `.capitalized` – kakubei Aug 01 '18 at 13:23
  • @kakubei Why you do negative vote. This method is for Sentance case. Capitalized will do every first character of the word to capital. Example String :- (THIS IS A BOY) `.capitalized` will return (This Is A Boy) and this method will return (This is a boy) Both are different. (Please do +ve Vote or Remove negative) – Ashu Aug 02 '18 at 05:17
  • You’re right @ashu, my apologies. However I can’t upvote until you edit the answer so maybe just make a small white space edit and I shall upvote it. Sorry again. – kakubei Aug 03 '18 at 07:45
  • No need to initialize a String with the first character. `return first.uppercased() + dropFirst()` or one liner return `(first?.uppercased() ?? "") + dropFirst()` – Leo Dabus May 22 '20 at 00:39
-1
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)
    }
}
john07
  • 562
  • 6
  • 16
-1

Add this line in viewDidLoad() method.

 txtFieldName.autocapitalizationType = UITextAutocapitalizationType.words
Pranit
  • 892
  • 12
  • 20
-1

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)
TheLegend27
  • 741
  • 7
  • 8
-3

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"

Hula
  • 51
  • 3