2014-11-22 84 views
5

我有一个字符串描述持有我的句子。我只想把第一个字母大写。我尝试了不同的事情,但其中大多数给我例外和错误。即时通讯使用的Xcode 6.首字母大写的句子(斯威夫特)

这里是我试过到目前为止

let cap = [description.substringToIndex(advance(0,1))] as String 
    description = cap.uppercaseString + description.substringFromIndex(1) 

它给了我:类型 'String.Index' 不符合协议 'IntegerLiteralConvertible'

我试图

func capitalizedStringWithLocale(locale:0) -> String 

但我就是无法弄清楚如何使它发挥作用。 任何想法?

回答

2
import Foundation 

// A lowercase string 
let description = "the quick brown fox jumps over the lazy dog." 

// The start index is the first letter 
let first = description.startIndex 

// The rest of the string goes from the position after the first letter 
// to the end. 
let rest = advance(first,1)..<description.endIndex 

// Glue these two ranges together, with the first uppercased, and you'll 
// get the result you want. Note that I'm using description[first...first] 
// to get the first letter because I want a String, not a Character, which 
// is what you'd get with description[first]. 
let capitalised = description[first...first].uppercaseString + description[rest] 

// Result: "The quick brown fox jumps over the lazy dog." 

您可能希望确保有至少一个字符在你的句子,然后再开始,否则你会得到一个运行时错误试图推动该指数超过字符串的结尾。

8

在夫特2,可以执行String(text.characters.first!).capitalizedString + String(text.characters.dropFirst())

+0

此外,如果你想要一个真正只首字母大写的字符串,如“约翰”或“李四”,而不是“约翰”和“美国能源部”,你可以做到以下几点: '字符串(text.characters .first!)。capitalizedString + String(text.characters.dropFirst())。lowercased()' – KingChintz 2017-06-28 03:53:51

3

另一种可能性在夫特3 -

extension String { 
    func capitalizeFirst() -> String { 
     let firstIndex = self.index(startIndex, offsetBy: 1) 
     return self.substring(to: firstIndex).capitalized + self.substring(from: firstIndex).lowercased() 
    } 
} 

编辑为夫特4从上方夫特3
警告代码 -

'substring(to :)'已弃用:请使用字符串切片下标 与'pa直至'操作员的最高范围。
'substring(from :)'已弃用:请使用字符串切片下标和'部分范围from'运算符。

斯威夫特4解决方案 -

extension String { 
    var capitalizedFirst: String { 
     guard !isEmpty else { 
      return self 
     } 

     let capitalizedFirstLetter = charAt(i: 0).uppercased() 
     let secondIndex    = index(after: startIndex) 
     let remainingString   = self[secondIndex..<endIndex] 

     let capitalizedString  = "\(capitalizedFirstLetter)\(remainingString)" 
     return capitalizedString 
    } 
} 
1

这里是如何做到这一点的斯威夫特4;以防万一,如果它有助于任何人:

extension String { 
    func captalizeFirstCharacter() -> String { 
     var result = self 

     let substr1 = String(self[startIndex]).uppercased() 
     result.replaceSubrange(...startIndex, with: substr1) 

     return result 
    } 
} 

它不会改变原来String

1
extension String { 
var capitalizedFirstLetter:String { 
    let string = self 
    return string.replacingCharacters(in: startIndex...startIndex, with: String(self[startIndex]).capitalized) 
} 

}

let newSentence = sentence.capitalizedFirstLetter 
0

对于一个或字符串每个单词,你可以使用字符串的.capitalized财产。

print("foo".capitalized) //prints: Foo 

print("foo foo foo".capitalized) //prints: Foo Foo Foo