獲取末尾兩個(gè)字符:
let sessionId = "this is a test"
let index = sessionId.index(sessionId.endIndex, offsetBy: -2)
let suffix = sessionId.substring(from: index)
最后結(jié)果為:“st”
獲取開(kāi)頭字符兩個(gè):
let sessionId = "this is a test"
let index = sessionId.index(sessionId.startIndex, offsetBy: 2)
let prefix = sessionId.substring(to: index)
獲取中間字符兩個(gè):
a,笨方法
let sessionId = "this is a test"
let index = sessionId.index(sessionId.startIndex, offsetBy: 5)
let prefix = sessionId.substring(to: index)
let index = sessionId.index(prefix.startIndex, offsetBy: -2)
b,直接用range截取
let subString1 = (swiftStringasNSString).substring(with: NSMakeRange(1,3))