问题
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!
回答1:
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()
}
}
回答2:
Swift 5 or later
extension StringProtocol {
var firstUppercased: String {
return prefix(1).uppercased() + dropFirst()
}
var firstCapitalized: String {
return prefix(1).capitalized + dropFirst()
}
}
Xcode 9 • Swift 4
extension StringProtocol {
var firstUppercased: String {
return prefix(1).uppercased() + dropFirst()
}
var firstCapitalized: String {
return String(prefix(1)).capitalized + dropFirst()
}
}
"Swift".first // "S"
"Swift".last // "t"
"hello world!!!".firstUppercased // "Hello world!!!"
"DŽ".firstCapitalized // "Dž"
"Dž".firstCapitalized // "Dž"
"dž".firstCapitalized // "Dž"
回答3:
Swift 3.0
for "Hello World"
nameOfString.capitalized
or for "HELLO WORLD"
nameOfString.uppercased
回答4:
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.
回答5:
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())
}
}
回答6:
For first character in word use .capitalized
in swift and for whole-word use .uppercased()
回答7:
Swift 2.0 (Single line):
String(nameOfString.characters.prefix(1)).uppercaseString + String(nameOfString.characters.dropFirst())
回答8:
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
回答9:
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.
回答10:
From Swift 3 you can easily use
textField.autocapitalizationType = UITextAutocapitalizationType.sentences
回答11:
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()
}
}
回答12:
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())
回答13:
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())
}
}
回答14:
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
}
}
回答15:
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
}
回答16:
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
}
}
回答17:
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
回答18:
Swift 4
func firstCharacterUpperCase() -> String {
if self.count == 0 { return self }
return prefix(1).uppercased() + dropFirst().lowercased()
}
回答19:
For swift 5, you can simple do like that:
yourString.firstUppercased
Sample: "abc" -> "Abc"
回答20:
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)
}
回答21:
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.
回答22:
Swift 3 Update
The replaceRange
func is now replaceSubrange
nameOfString.replaceSubrange(nameOfString.startIndex...nameOfString.startIndex, with: String(nameOfString[nameOfString.startIndex]).capitalized)
回答23:
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.
回答24:
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: " ")
}
}
回答25:
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"
回答26:
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()
}
}
回答27:
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)
}
}
来源:https://stackoverflow.com/questions/26306326/swift-apply-uppercasestring-to-only-the-first-letter-of-a-string