截取前 n 个字符:
let str = "Hello, Swift!"
let prefix = str.prefix(5)
print(prefix) // "Hello"
截取后 n 个字符:
let str = "Hello, Swift!"
let suffix = str.suffix(6)
print(suffix) // "Swift!"
截取指定范围内的字符:
let str = "Hello, Swift!"
let range = str.index(str.startIndex, offsetBy: 7)..<str.endIndex
let subString = str[range]
print(subString) // "Swift!"
截取从某个位置到末尾的字符:
let str = "Hello, Swift!"
let index = str.index(str.startIndex, offsetBy: 7)
let subString = str[index...]
print(subString) // "Swift!"
从最后一个指定“.”字符开始截取,到字符串结束:文章来源:https://www.toymoban.com/news/detail-634264.html
let str = "http://www.free.com/346345647457.png"
if let dotIndex = str.lastIndex(of: ".") {
let fileExtension = str[dotIndex+1..<str.endIndex]
print(fileExtension) // "png"文章来源地址https://www.toymoban.com/news/detail-634264.html
到了这里,关于swift3.0 废弃 swift 4.0 以后字符串截取的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!