下面介绍2种swift的字符串截取方法,实际上用到了substringFromIndex
, substringToIndex
, substringWithRange
- 将String转化为NSString再截取,代码如下:
var s="1234567890"
var ns1=(s as NSString).substringFromIndex(5)
var ns2=(s as NSString).substringToIndex(4)
var ns3=(s as NSString).substringWithRange(NSMakeRange(4, 1))
println(ns1)//67890
println(ns2)//1234
println(ns3)//5
- 直接调用
String
的对应方法(推荐使用该方法),由于String
对应的方法参数是String.Index
类型而非Int
类型,所以我们首先要创建String.Index
类型参数值,代码如下:
// var s="1234567890"
// let index = advance(s.startIndex, 5) swift 1.x
//let index2 = advance(s.endIndex, -6); swift 1.x
var s="1234567890"
let index = s.startIndex.advancedBy(5) //swift 2.0+
let index2 = s.endIndex.advancedBy(-6) //swift 2.0+
var range = Range<String.Index>(start: index2,end: index)
var s1:String=s.substringFromIndex(index)
var s2:String=s.substringToIndex(index2)
var s3=s.substringWithRange(range)
print(s1)//67890
print(s2)//1234
print(s3)//5
// 扩展String
extension String {
subscript (r: Range<Int>) -> String {
get {
let startIndex = self.startIndex.advancedBy(r.startIndex)
let endIndex = self.startIndex.advancedBy(r.endIndex)
return self[Range(start: startIndex, end: endIndex)]
}
}
}
var s4 = s[2...4]
print(s4);//345
通过String
定义可以看出属性Index
是个结构体,具体代码如下:
extension String : CollectionType {
struct Index : BidirectionalIndexType, Comparable, Reflectable {
func successor() -> String.Index
func predecessor() -> String.Index
func getMirror() -> MirrorType
}
var startIndex: String.Index { get }
var endIndex: String.Index { get }
subscript (i: String.Index) -> Character { get }
func generate() -> IndexingGenerator<String>
}
最后,有网友回复加一个set方法,感觉更完美,就都写到这里:
set {
let startIndex = self.startIndex.advancedBy(range.startIndex)
let endIndex = self.startIndex.advancedBy(range.endIndex)
let strRange = Range(startIndex..<endIndex)
self.replaceRange(strRange, with: newValue)
}
**转自: **