Swift 3 String
has three methods for string interception:
str.substring(to: String.Index)str.substring(from: String.Index)str.substring(with: Range<String.Index>)
Examples used to do the demonstration:
var str = "Hello, World"
Str.substring (To:String.Index)
This method intercepts the index specified by the parameter from the beginning of the string to
.
let index = str.index(str.startIndex, offsetBy: 5) //索引为从开始偏移5个位置str.substring(to: index) // 获取Hello
SUBSTRING (from:String.Index)
This method intercepts the from
end of the string from the index specified by the parameter.
let index = str.index(str.startIndex, offsetBy: 7) //索引从开始偏移7个位置str.substring(from: index) // 输出World
Str.substring (with:range<string.index>)
This method intercepts the specified string range, which is specified by range. Similar to the Swift 2 String.substringWithRange
.
let start = str.index(str.startIndex, offsetBy: 7) //索引从开始偏移7个位置let end = str.index(str.endIndex, offsetBy: -3) //所有从末尾往回偏移三个位置let range = start..<endstr.substring(with: range) // 输出Wo
Swift intercept string (reprint)