我怎样才能得到字符串的第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,请参阅文档注释讨论
当前回答
斯威夫特5.1.3:
添加一个String扩展名:
extension String {
func stringAt(_ i: Int) -> String {
return String(Array(self)[i])
}
func charAt(_ i: Int) -> Character {
return Array(self)[i]
}
}
let str = "Teja Kumar"
let str1: String = str.stringAt(2) //"j"
let str2: Character = str.charAt(5) //"k"
其他回答
你可以使用SwiftString (https://github.com/amayne/SwiftString)来做这件事。
"Hello, world!"[0] // H
"Hello, world!"[0...4] // Hello
免责声明:我写了这个扩展
Swift 3:另一个解决方案(在操场测试)
extension String {
func substr(_ start:Int, length:Int=0) -> String? {
guard start > -1 else {
return nil
}
let count = self.characters.count - 1
guard start <= count else {
return nil
}
let startOffset = max(0, start)
let endOffset = length > 0 ? min(count, startOffset + length - 1) : count
return self[self.index(self.startIndex, offsetBy: startOffset)...self.index(self.startIndex, offsetBy: endOffset)]
}
}
用法:
let txt = "12345"
txt.substr(-1) //nil
txt.substr(0) //"12345"
txt.substr(0, length: 0) //"12345"
txt.substr(1) //"2345"
txt.substr(2) //"345"
txt.substr(3) //"45"
txt.substr(4) //"5"
txt.substr(6) //nil
txt.substr(0, length: 1) //"1"
txt.substr(1, length: 1) //"2"
txt.substr(2, length: 1) //"3"
txt.substr(3, length: 1) //"4"
txt.substr(3, length: 2) //"45"
txt.substr(3, length: 3) //"45"
txt.substr(4, length: 1) //"5"
txt.substr(4, length: 2) //"5"
txt.substr(5, length: 1) //nil
txt.substr(5, length: -1) //nil
txt.substr(-1, length: -1) //nil
我也有同样的问题。简单地这样做:
var aString: String = "test"
var aChar:unichar = (aString as NSString).characterAtIndex(0)
swift字符串类不提供在特定索引处获取字符的能力,因为它本身支持UTF字符。UTF字符在内存中的可变长度使得直接跳转到字符是不可能的。这意味着每次都必须手动遍历字符串。
您可以扩展String以提供一个方法,该方法将遍历字符,直到您需要的索引
extension String {
func characterAtIndex(index: Int) -> Character? {
var cur = 0
for char in self {
if cur == index {
return char
}
cur++
}
return nil
}
}
myString.characterAtIndex(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"
:-)