Swift 字符串操作(截取,去白等)
2018-10-29 本文已影响15人
fruit6
开发过程中经常需要对字符串进行一些操作,比如获取字符串长度,截取等等,下面写一个string的扩展,让我们更加便捷的对字符串进行这些操作。
extension String {
func toInt() -> Int? {
return Int(self)
}
func toFloat() -> Float? {
return Float(self)
}
func toDouble() -> Double? {
return Double(self)
}
//MARK:- 去除字符串两端的空白字符
func trim() -> String {
return self.trimmingCharacters(in: CharacterSet.whitespaces)
}
//MARK:- 字符串长度
func length() -> Int {
return self.characters.count
}
func indexOf(_ target: Character) -> Int? {
return self.index(of: target)?.encodedOffset
}
func subString(to: Int) -> String {
let endIndex = String.Index.init(encodedOffset: to)
let subStr = self[self.startIndex..<endIndex]
return String(subStr)
}
func subString(from: Int) -> String {
let startIndex = String.Index.init(encodedOffset: from)
let subStr = self[startIndex..<self.endIndex]
return String(subStr)
}
func subString(start: Int, end: Int) -> String {
let startIndex = String.Index.init(encodedOffset: start)
let endIndex = String.Index.init(encodedOffset: end)
return String(self[startIndex..<endIndex])
}
func subString(range: Range<String.Index>) -> String {
return String(self[range.lowerBound..<range.upperBound])
}
}
如果对你有帮助,请给个喜欢😁