Answers:
包括与API准则一致的变异版本和非变异版本。
斯威夫特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()
}
}
斯威夫特4:
extension String {
func capitalizingFirstLetter() -> String {
return prefix(1).uppercased() + self.lowercased().dropFirst()
}
mutating func capitalizeFirstLetter() {
self = self.capitalizingFirstLetter()
}
}
Foundation
.uppercaseString
用于此操作
.capitalized
现在。另请注意capitalizedStringWith(_ locale:)
Swift 5.1或更高版本
extension StringProtocol {
var firstUppercased: String { prefix(1).uppercased() + dropFirst() }
var firstCapitalized: String { prefix(1).capitalized + dropFirst() }
}
迅捷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ž"
UITextField
观察者一起使用时,似乎会导致内存泄漏UITextFieldTextDidChangeNotification
。
斯威夫特3.0
对于“ Hello World”
nameOfString.capitalized
或“ HELLO WORLD”
nameOfString.uppercased
迅捷4.0
string.capitalized(with: nil)
要么
string.capitalized
但是,每个单词的首字母大写
苹果的文档:
大写字符串是一个字符串,其中每个单词的第一个字符均更改为其相应的大写值,而所有其余字符均设置为其相应的小写值。“单词”是由空格,制表符或行终止符分隔的任何字符序列。不考虑某些常见的单词定界标点,因此此属性通常可能无法为多单词字符串产生所需的结果。有关其他信息,请参见getLineStart(_:end:contentsEnd:for :)方法。
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()
对于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())
}
}
isEmpty
和初始化字符串以替换其中任何一个。您可以简单地解开第一个字符,以防万一失败则返回nil。可以简化为var firstCharacterUpperCase: String? { guard let first = first else { return nil } return lowercased().replacingCharacters(in: startIndex...startIndex, with: first.uppercased()) }
Swift 2.0(单行):
String(nameOfString.characters.prefix(1)).uppercaseString + String(nameOfString.characters.dropFirst())
.localizedLowercaseString
在末尾添加了使其与aNYsTring这样的字符串一起使用。String(nameOfString.characters.prefix(1)).uppercaseString + String(nameOfString.characters.dropFirst()).localizedLowercaseString
斯威夫特3(xcode 8.3.3)
将字符串的所有首字符大写
let str = "your string"
let capStr = str.capitalized
//Your String
大写所有字符
let str = "your string"
let upStr = str.uppercased()
//YOUR STRING
字符串的仅大写第一个字符
var str = "your string"
let capStr = String(str.characters.prefix(1)).uppercased() + String(str.characters.dropFirst())
//Your string
迅速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()
}
}
与你的弦一起使用
let test = "the rain in Spain"
print(test.capitalizingFirstLetter())
我正在用Kirsteins的解决方案复制第一个字符。这将大写第一个字符,而不会出现双重:
var s: String = "hello world"
s = prefix(s, 1).capitalizedString + suffix(s, countElements(s) - 1)
我不知道它的效率是高还是低,我只知道它能给我带来理想的结果。
countElements
仅为count
。
这是Swift 5的一个版本,如果第一个字母已经是大写或没有大小写概念,则使用Unicode标量属性API进行纾困:
extension String {
func firstLetterUppercased() -> String {
guard let first = first, first.isLowercase else { return self }
return String(first).uppercased() + dropFirst()
}
}
return first.uppercased() + dropFirst()
或一支班轮(first?.uppercased() ?? "") + dropFirst()
在Swift 3.0中(这比接受的答案要快一些,也更安全):
extension String {
func firstCharacterUpperCase() -> String {
if let firstCharacter = characters.first {
return replacingCharacters(in: startIndex..<index(after: startIndex), with: String(firstCharacter).uppercased())
}
return ""
}
}
nameOfString.capitalized将不起作用,它将大写句子中的每个单词
我的解决方案:
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
}
结合上面的答案,我写了一个小扩展名,将每个单词的首字母大写(因为这就是我要查找的内容,并认为其他人可以使用它)。
我谦虚地提出:
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
}
}
这是我一步一步完成的方式,类似于@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)
}
如果要大写字符串的每个单词,可以使用此扩展名
斯威夫特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: " ")
}
}
用过的
print("simple text example".wordUppercased) //output:: "Simple Text Example"
.capitalized
如果您的字符串全部大写,则下面的方法将起作用
labelTitle.text = remarks?.lowercased().firstUppercased
此扩展程序将帮助您
extension StringProtocol {
var firstUppercased: String {
guard let first = first else { return "" }
return String(first).uppercased() + dropFirst()
}
}
.capitalized
.capitalized
将返回(This Is A Boy),并且此方法将返回(This Is Boyy)两者都不同。(请+投票或删除否定词)
return first.uppercased() + dropFirst()
或一次班轮往返(first?.uppercased() ?? "") + dropFirst()
.capitalizedString
在Xcode 7 Beta 4中不再可用。字符串在Swift 2.0中有所改变。