如何获取字符串的第n个字符?我试过括号([])存取器没有运气。
var string = "Hello,world!" var firstChar = string[0] // Throws error
extension String { subscript (i: Int) -> Character { return self[self.startIndex.advancedBy(i)] } subscript (i: Int) -> String { return String(self[i] as Character) } subscript (r: Range<Int>) -> String { let start = startIndex.advancedBy(r.startIndex) let end = start.advancedBy(r.endindex - r.startIndex) return self[Range(start ..< end)] } }
现在,这些都等于true。
"abcde"[0] == "a" "abcde"[0...2] == "abc" "abcde"[2..<4] == "cd"