Dưới đây là những gì tôi nghĩ ra có vẻ như hiệu quả nhưng tôi mở cho mọi thứ tốt hơn.
func firstCharacterUpperCase(sentenceToCap:String) -> String {
//break it into an array by delimiting the sentence using a space
var breakupSentence = sentenceToCap.componentsSeparatedByString(" ")
var newSentence = ""
//Loop the array and concatinate the capitalized word into a variable.
for wordInSentence in breakupSentence {
newSentence = "\(newSentence) \(wordInSentence.capitalizedString)"
}
// send it back up.
return newSentence
}
hoặc nếu tôi muốn sử dụng như một phần mở rộng của chuỗi lớp.
extension String {
var capitalizeEachWord:String {
//break it into an array by delimiting the sentence using a space
var breakupSentence = self.componentsSeparatedByString(" ")
var newSentence = ""
//Loop the array and concatinate the capitalized word into a variable.
for wordInSentence in breakupSentence {
newSentence = "\(newSentence) \(wordInSentence.capitalizedString)"
}
// send it back up.
return newSentence
}
}
Một lần nữa, mọi thứ đều được chào đón.
Nguồn
2015-03-25 16:38:11
var someString = "lol"; someString.capitalized // "Lol" – Alexander
Một vài người khác đã nêu chi tiết tùy chọn này bên dưới. ;) –