iOS Swift 基础类型转换相关
2020-06-28 本文已影响0人
A_rcher34
1 字符串截取
1.1 提取单个字符:
let str = "This is test String!"
let subStr:Character = str[str.index(str.startIndex,offsetBy: 8)
print(subStr) //print: t
1.2 截取前三个字符:
//方法一
let str = "0123456789"
let subStr = str.prefix(3)
print(subStr)//输出012
//方法二
let str = "0123456789"
let endIndex = str.index(str.startIndex, offsetBy: 3)
let newStr = String(str[..<endIndex])
print(newStr)//输出012
1.3 截取后三个字符:
//方法一
let str = "0123456789"
let subStr = str.suffix(3)
print(subStr)//输出789
//方法二
let str = "0123456789"
let startIndex = str.index(str.endIndex, offsetBy: -3)
let newStr = String(str[startIndex..<str.endIndex])
print(newStr)//输出789
1.4 提取多个字符:
有两种方法:第二种方法虽然看起来步骤会多一些,但是对于寻址操作来说,数组的寻址速度还是远优于String自带方法的寻址速度。所以,当要执行循环寻址的操作时,建议使用第二种方法。
// 方法1
let s = "This is test String!"
let leftIndex = s.index(s.startIndex,offsetBy: 8)
let rightIndex = s.index(s.startIndex,offsetBy: 12)
print(String(s[leftIndex..<rightIndex])) //print: test
// 方法2
let s = "This is test String!"
let arr = Array(s)
let subArr = arr[8..<12]
let subStr:String = subArr.map{String.init($0)}.joined()
print(subStr) //print:test
参考文献
字符串截取