我怎样才能得到字符串的第n个字符?我尝试了括号([])访问器,没有运气。
var string = "Hello, world!"
var firstChar = string[0] // Throws error
错误:'下标'是不可用的:不能下标String与Int,请参阅文档注释讨论
我怎样才能得到字符串的第n个字符?我尝试了括号([])访问器,没有运气。
var string = "Hello, world!"
var firstChar = string[0] // Throws error
错误:'下标'是不可用的:不能下标String与Int,请参阅文档注释讨论
当前回答
到目前为止,下标(_:)不可用。就像我们不能这么做一样
str[0]
与字符串。我们必须提供"String "。指数” 但是,我们如何给出我们自己的索引号呢,我们可以用,
string[str.index(str.startIndex, offsetBy: 0)]
其他回答
顺便说一句,有几个函数可以直接应用于String的字符链表示,像这样:
var string = "Hello, playground"
let firstCharacter = string.characters.first // returns "H"
let lastCharacter = string.characters.last // returns "d"
结果类型为Character,但可以将其转换为String。
或:
let reversedString = String(string.characters.reverse())
// returns "dnuorgyalp ,olleH"
:-)
我想指出的是,如果你有一个很大的字符串,并且需要从中随机访问许多字符,你可能想要支付额外的内存成本,并将字符串转换为一个数组以获得更好的性能:
// Pay up front for O(N) memory
let chars = Array(veryLargeString.characters)
for i in 0...veryLargeNumber {
// Benefit from O(1) access
print(chars[i])
}
使用字符就可以了。您可以快速地将字符串转换为字符数组,可以由CharacterView方法操作。
例子:
let myString = "Hello World!"
let myChars = myString.characters
(完整的CharacterView文档)
(在Swift 3中测试)
斯威夫特4.2
这个答案是理想的,因为它在一个扩展中扩展了String及其所有子序列(Substring)
public extension StringProtocol {
public subscript (i: Int) -> Element {
return self[index(startIndex, offsetBy: i)]
}
public subscript (bounds: CountableClosedRange<Int>) -> SubSequence {
let start = index(startIndex, offsetBy: bounds.lowerBound)
let end = index(startIndex, offsetBy: bounds.upperBound)
return self[start...end]
}
public subscript (bounds: CountableRange<Int>) -> SubSequence {
let start = index(startIndex, offsetBy: bounds.lowerBound)
let end = index(startIndex, offsetBy: bounds.upperBound)
return self[start..<end]
}
public subscript (bounds: PartialRangeUpTo<Int>) -> SubSequence {
let end = index(startIndex, offsetBy: bounds.upperBound)
return self[startIndex..<end]
}
public subscript (bounds: PartialRangeThrough<Int>) -> SubSequence {
let end = index(startIndex, offsetBy: bounds.upperBound)
return self[startIndex...end]
}
public subscript (bounds: CountablePartialRangeFrom<Int>) -> SubSequence {
let start = index(startIndex, offsetBy: bounds.lowerBound)
return self[start..<endIndex]
}
}
使用
var str = "Hello, playground"
print(str[5...][...5][0])
// Prints ","
我刚想出了一个巧妙的变通办法
var firstChar = Array(string)[0]