Swift 中字符串截取的几种常见情况

  1. 截取前 n 个字符:

let str = "Hello, Swift!"
let prefix = str.prefix(5)
print(prefix) // "Hello"
  1. 截取后 n 个字符:

let str = "Hello, Swift!"
let suffix = str.suffix(6)
print(suffix) // "Swift!"
  1. 截取指定范围内的字符:

let str = "Hello, Swift!"
let range = str.index(str.startIndex, offsetBy: 7)..
  1. 截取从某个位置到末尾的字符:

let str = "Hello, Swift!"
let index = str.index(str.startIndex, offsetBy: 7)
let subString = str[index...]
print(subString) // "Swift!"
  1. 从最后一个指定“.”字符开始截取,到字符串结束:

let str = "http://www.free.com/346345647457.png"
if let dotIndex = str.lastIndex(of: ".") {
    let fileExtension = str[dotIndex+1..

你可能感兴趣的:(iOS,Swift,swift,ios)