我正在尝试从Swift5中给定的输入字符串中提取一个部分字符串。就像字符串中的2到5个字母。
我确信,像inputString[2...5]这样简单的东西会起作用,但我只让它像这样工作:
String(input[(input.index(input.startIndex, offsetBy: 2))..<(input.index(input.endIndex, offsetBy: -3))])..。它仍然使用相对位置(endIndex-3而不是位置#5)
现在我想知道我到底是在哪里搞砸的。
人们通常如何从"abcdefgh“的绝对位置提取"cde”?
发布于 2019-06-15 22:24:37
我为速记子字符串编写了以下扩展,而不必在主代码中处理索引和转换:
extension String {
func substring(from: Int, to: Int) -> String {
let start = index(startIndex, offsetBy: from)
let end = index(start, offsetBy: to - from + 1)
return String(self[start ..< end])
}
}
let testString = "HelloWorld!"
print(testString.substring(from: 0, to: 4)) // 0 to 4 inclusive输出Hello。
https://stackoverflow.com/questions/56614440
复制相似问题