Swift字符串的截取

substring在swift中的对应方法

1.截取前几位字符

let string = "abcdef1234.pdf"
let prefix = string.prefix(3)
print(prefix)
//打印结果:abc

2.截取后几位字符

let string = "abcdef1234.pdf"
let suffix = string.suffix(3)
print(suffix)
//打印结果:pdf

3.去掉前几位字符

let string = "abcdef1234.pdf"
let dropfirst = string.dropFirst(3)
print(dropfirst)
//打印结果:def1234.pdf

4.去掉后几位字符

let string = "abcdef1234.pdf"
let dropLast = string.dropLast(4)
print(dropLast)
//打印结果:abcdef1234

5.截取字符串中间的字符

let string = "abcdef1234.pdf"
let numStr = string.dropFirst(6).prefix(4)
print(numStr)
//或者
if let index1 = string.lastIndex(of: "1"),
   let index2 = string.lastIndex(of: "4") {
    let num = String(string[index1...index2])
    print(num)
}
//打印结果:1234

你可能感兴趣的:(Swift字符串的截取)