Swift中如果想获取字符串中的某个字符,通过Index索引获取,先来简单看一下几个简单的字符串获取字符的方法:
var str="My name is FlyElephant"
//start
var char=str.characters[str.startIndex]
print("\(char)")
//middle
var advance=str.characters[str.startIndex.advancedBy(3)]
print("\(advance)")
//end
var end=str.characters[str.endIndex.predecessor()]
print("\(end)")
var startIndex=str.startIndex.advancedBy(0)
var endIndex=str.startIndex.advancedBy(6)
var rangeContent=str[Range(startIndex...endIndex)]
print("\(rangeContent)")
第一个方法获取的是第一个字符,如果想往后获取,需要通过advancedBy往后获取,注意如果获取最后一个字符,还需要调用一下predecessor方法:
我们来看一下下面的实现方式:
var exChar:Character=str[0]
print("Extension:\(exChar)")
var stContent:String=str[3]
print("Extension:\(stContent)")
var range=Range(11...21)
var strRange=str[range]
print("Extension:\(strRange)")
获取结果:
上面的写法比较简单,我们需要扩展String,代码参考如下:
extension String {
subscript(index:NSInteger)->Character {
return self[self.startIndex.advancedBy(index)]
}
subscript(index:NSInteger)->String {
return String(self[index] as Character)
}
subscript(range:Range<NSInteger>)->String {
let start = startIndex.advancedBy(range.startIndex)
let end = start.advancedBy(range.endIndex-range.startIndex)
return self[Range(start..<end)]
}
}
Swift 3.0 扩展方法修改如下:
extension String {
subscript(index: Int) -> Character {
let position = self.index(self.startIndex, offsetBy: index)
return self[position]
}
subscript(index: Int) -> String {
return String(self[index] as Character)
}
subscript(range: Range<Int>) -> String {
let start = self.index(self.startIndex, offsetBy: range.lowerBound)
let end = self.index(start, offsetBy: range.upperBound - range.lowerBound)
return self[Range(start..<end)]
}
}
字符串转为Bool也可以扩展:
var boolValue: Bool {
return NSString(string: self).boolValue
}
func toBool() -> Bool? {
switch self {
case "True", "true", "yes", "1":
return true
case "False", "false", "no", "0":
return false
default:
return nil
}
}