使用swift开发,一定会对 String 的截取感到不适应,本文通过类拓展的方式给String 类型的字符串增加了一些截取方法,简单实用
先看看实用效果,有没有很简单!!!
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let str = "hello,swift!"
print(str[1]) //打印结果: e
print(str[2,4])//打印结果: llo
print(str[1...2])//打印结果: el
print(str.subString(to: 3))//打印结果: hel
print(str.subString(from: 3))//打印结果: lo,swift!
print(str.subString(location: 1, length: 3))//打印结果: ell
}
实现方法
extension String {
/// 截取 from 位置后的所有字符,from 超过字符串长度,返回空字符 ""
func subString(from: Int) -> String {
if from >= self.characters.count {
return ""
}
let rang = self.index(startIndex, offsetBy: from)..<self.endIndex
return self[rang]
}
/// 从起始位置开始截取到 to 位置的所有字符,to 超过字符串长度,返回整个字符串
func subString(to: Int) -> String {
if to >= self.characters.count {
return self;
}
let rang = self.startIndex..<self.index(startIndex, offsetBy: to)
return self[rang]
}
/// 截取 location 位置后的 length位长度的字符,location 超过字符串长度,返回空字符 "";
/// location + length 超过字符串长度,返回 location 位置后的所有字符
func subString(location:Int, length:Int) -> String {
if location >= self.characters.count {
return ""
}
if location + length >= self.characters.count {
return self
}
let locationIndex = self.index(startIndex, offsetBy: location)
let range = locationIndex..<self.index(locationIndex, offsetBy: length)
return self[range]
}
/// 下标的方式截取字符串; string[1,3] 截取 1~3位的字符串
subscript(begin: Int, end:Int) -> String {
if begin >= self.characters.count {
return ""
}
if end >= self.characters.count {
return subString(from: begin)
}
let range = self.index(startIndex, offsetBy: begin)...self.index(startIndex, offsetBy: end)
return self[range]
}
/// 下标的方式截取字符串; string[1...3] 截取 1~3位的字符串
subscript(range:ClosedRange<Int>) -> String {
if range.lowerBound >= self.characters.count {
return ""
}
if range.upperBound >= self.characters.count {
return subString(from: range.lowerBound)
}
let range = self.index(startIndex, offsetBy: range.lowerBound )...self.index(startIndex, offsetBy: range.upperBound)
return self[range]
}
/// 下标的方式截取字符串; string[1] 截取 位置为1 处的字符
subscript(idx: Int) ->String {
return subString(location: idx, length: 1)
}
}
如有疑问,欢迎评论交流!