Swift Range和字符串截取
BetterString.swift
Swift - String与NSString的区别,以及各自的使用场景
swift - String 子串
问题:使用属性字符串时需要设置NSRange,但swift中String和NSRange配合使用比较麻烦。写了两个方法:
extension String {
/// 截取NSRange范围的子字符串
func subString(with range: NSRange) -> String {
// if range.location < 0 {
// return ""
// }
// if let start = index(startIndex, offsetBy: range.location, limitedBy: endIndex), let end = index(startIndex, offsetBy: range.location + range.length, limitedBy: endIndex) {
// return String(self[start..<end])
// }
// return ""
let text = self as NSString
let subStr = text.substring(with: range) as String
return subStr
}
/// 获取子字符串的范围NSRange
func range(of subString: String) -> NSRange {
let text = self as NSString
return text.range(of: subString)
}
}
网友评论