[Swift] 极其难用的 字符串截取

2022-07-07  本文已影响0人  巨馍蘸酱

个人吐槽一下, 相对其他语言来说, Swift 的字符串操作极其难用

let value = "01234567890abc"
value.prefix(6) // 012345
value.suffix(4) // 0abc

value.prefix(upTo: value.firstIndex(of: "4")!) // 0123
value.prefix(through: value.firstIndex(of: "4")!) // 01234

let r: Range<String.Index> = value.range(of: "789")!

value.prefix(upTo: r.lowerBound) // 0123456
value.prefix(upTo: r.upperBound) // 0123456789

value.prefix(through: r.lowerBound) // 01234567
value.prefix(through: r.upperBound) // 01234567890

let location: String.IndexDistance = value.distance(from: value.startIndex, to: r.lowerBound) // Int 起始位置 7
let lenth: String.IndexDistance = value.distance(from: r.lowerBound, to: r.upperBound) // Int 长度 3
let str: Substring = value[value.startIndex ..< r.lowerBound] // 0123456
value[r.lowerBound ..< r.upperBound] // 789
value[r.upperBound ..< value.endIndex] // 0abc

let nsrange = NSRange(location: location, length: lenth)
nsrange.location // 7
nsrange.length // 3
nsrange.lowerBound // 7
nsrange.upperBound // 10
上一篇 下一篇

猜你喜欢

热点阅读