3 回答
TA贡献1780条经验 获得超1个赞
将子字符串(Swift 3)转换为字符串切片(Swift 4)
Swift 3、4中的示例:
let newStr = str.substring(to: index) // Swift 3
let newStr = String(str[..<index]) // Swift 4
let newStr = str.substring(from: index) // Swift 3
let newStr = String(str[index...]) // Swift 4
let range = firstIndex..<secondIndex // If you have a range
let newStr = = str.substring(with: range) // Swift 3
let newStr = String(str[range]) // Swift 4
TA贡献2041条经验 获得超4个赞
您应将一侧留空,因此命名为“ partial range”。
let newStr = str[..<index]
运算符的部分范围相同,只是将另一侧留空:
let newStr = str[index...]
请记住,这些范围运算符返回Substring。如果要将其转换为字符串,请使用String的初始化函数:
let newStr = String(str[..<index])
您可以在此处阅读有关新子字符串的更多信息。
TA贡献1772条经验 获得超8个赞
斯威夫特5、4
用法
let text = "Hello world"
text[0] // H
text[...3] // "Hell"
text[6..<text.count] // world
text[NSRange(location: 6, length: 3)] // wor
码
import Foundation
public extension String {
subscript(value: Int) -> Character {
self[index(at: value)]
}
}
public extension String {
subscript(value: NSRange) -> Substring {
self[value.lowerBound..<value.upperBound]
}
}
public extension String {
subscript(value: CountableClosedRange<Int>) -> Substring {
self[index(at: value.lowerBound)...index(at: value.upperBound)]
}
subscript(value: CountableRange<Int>) -> Substring {
self[index(at: value.lowerBound)..<index(at: value.upperBound)]
}
subscript(value: PartialRangeUpTo<Int>) -> Substring {
self[..<index(at: value.upperBound)]
}
subscript(value: PartialRangeThrough<Int>) -> Substring {
self[...index(at: value.upperBound)]
}
subscript(value: PartialRangeFrom<Int>) -> Substring {
self[index(at: value.lowerBound)...]
}
}
private extension String {
func index(at offset: Int) -> String.Index {
index(startIndex, offsetBy: offset)
}
}
- 3 回答
- 0 关注
- 798 浏览
添加回答
举报