首页 > 编程语言 > 详细

Swift截取字符串(转载)

时间:2017-05-16 12:13:13      阅读:462      评论:0      收藏:0      [点我收藏+]

Swift 3的String有三个方法用于做字符串截取:

str.substring(to: String.Index)
str.substring(from: String.Index)
str.substring(with: Range<String.Index>)

用于做示范的示例:

var str = "Hello, World"

str.substring(to: String.Index)

这个方法会从字符串的开始截取到to参数指定的索引。

let index = str.index(str.startIndex, offsetBy: 5)  //索引为从开始偏移5个位置
str.substring(to: index)  // 获取Hello

substring(from: String.Index)

这个方法会从from参数指定的索引截取到字符串的末尾。

let index = str.index(str.startIndex, offsetBy: 7) //索引从开始偏移7个位置
str.substring(from: index)  // 输出World

str.substring(with: Range<String.Index>)

这个方法是截取指定的字符串范围,范围由Range指定。类似于Swift 2的String.substringWithRange

let start = str.index(str.startIndex, offsetBy: 7)  //索引从开始偏移7个位置
let end = str.index(str.endIndex, offsetBy: -3)   //所有从末尾往回偏移三个位置
let range = start..<end

str.substring(with: range)  // 输出Wo

Swift截取字符串(转载)

原文:http://www.cnblogs.com/lc901221/p/6860459.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!