extension String {
/// range转换为NSRange
func nsRange(from range: Range) -> NSRange {
return NSRange(range, in: self)
}
}
使用示例
let languages = "Java,Swift,Objective-C"
let one = "Swift"
let range = languages.range(of: one)
let nsRange = "".nsRange(from: range!)
print(nsRange) // {5, 5}
extension String {
/// NSRange转化为range
func range(from nsRange: NSRange) -> Range? {
guard
let from16 = utf16.index(utf16.startIndex, offsetBy: nsRange.location, limitedBy: utf16.endIndex),
let to16 = utf16.index(from16, offsetBy: nsRange.length, limitedBy: utf16.endIndex),
let from = String.Index(from16, within: self),
let to = String.Index(to16, within: self)
else { return nil }
return from ..< to
}
}
字符串其他用法示例
1.在字符串中查找另一字符串首次出现的位置(或最后一次出现位置)
extension String {
///(如果backwards参数设置为true,则返回最后出现的位置)
func positionOf(sub:String, backwards:Bool = false)->Int {
// 如果没有找到就返回-1
var pos = -1
if let range = range(of:sub, options: backwards ? .backwards : .literal ) {
if !range.isEmpty {
pos = self.distance(from:startIndex, to:range.lowerBound)
}
}
return pos
}
}
使用示例
let str1 = "欢迎访问hangge.com。hangge.com做最好的开发者知识平台"
let str2 = "hangge"
let position1 = str1.positionOf(sub: str2)
print("子字符串第一次出现的位置是:\(position1)")
// 子字符串第一次出现的位置是:4
let position2 = str1.positionOf(sub: str2, backwards: true)
print("子字符串最后一次出现的位置是:\(position2)")
// 子字符串最后一次出现的位置是:15
2.使用下标截取字符串
extension String {
/// 使用下标截取字符串 例: "示例字符串"[0..<2] 结果是 "示例"
subscript (r: Range) -> String {
get {
if (r.lowerBound > count) || (r.upperBound > count) { return "截取超出范围" }
let startIndex = self.index(self.startIndex, offsetBy: r.lowerBound)
let endIndex = self.index(self.startIndex, offsetBy: r.upperBound)
return String(self[startIndex..
3.字符串截取第一个到第任意位置
extension String {
/// 截取第一个到第任意位置
///
/// - Parameter end: 结束的位值
/// - Returns: 截取后的字符串
func stringCut(end: Int) ->String{
if !(end < self.count) { return "截取超出范围" }
let sInde = index(startIndex, offsetBy: end)
return String(self[...sInde])
}
}
// 使用示例
let str = "示例字符串".stringCut(end: 2)
print(str) // 示例字
4.截取第任意位置到结束
extension String {
/// 截取第任意位置到结束
///
/// - Parameter end:
/// - Returns: 截取后的字符串
func stringCutToEnd(start: Int) -> String {
if !(start < count) { return "截取超出范围" }
let sRang = index(startIndex, offsetBy: start)
//return substring(with: sRang)
return String(self[sRang...])
}
}
// 使用示例
let str = "示例字符串".stringCutToEnd(start: 3)
print(str) // 符串
5.字符串任意位置插入
extension String {
/// 字符串任意位置插入
///
/// - Parameters:
/// - content: 插入内容
/// - locat: 插入的位置
/// - Returns: 添加后的字符串
func stringInsert(content: String,locat: Int) -> String {
if !(locat < count) { return "截取超出范围" }
let str1 = stringCut(end: locat)
let str2 = stringCutToEnd(start: locat+1)
return str1 + content + str2
}
}
// 示例
let str = "示例字符串".stringInsert(content: ",", locat: 1)
print(str) // 示例,字符串
6.字符串包含,前缀,后缀
let languages = "Java,Swift,Objective-C"
let flag1 = languages.contains("Java") // true
let flag2 = languages.hasPrefix("Swift") // false
let flag3 = languages.hasPrefix("Java") // true
let flag4 = languages.hasSuffix("Objective-C")// true
7.字符串大小写转换,首字符大写转换
let languages = "Java,Swift,Objective-C,js"
// 全部转换成大写
let languages_up = languages.uppercased() // JAVA,SWIFT,OBJECTIVE-C
// 全部转换成小写
let languages_lower = languages.lowercased() // java,swift,objective-c
// 首字母大写
let languages_first = languages.capitalized // Java,Swift,Objective-C,Js
8.字符串是否为空
let stringA = ""
if stringA.isEmpty {
print( "stringA 是空的" )
} else {
print( "stringA 不是空的" )
}
9.剔除字符串首尾空格
var stringA = " Swift Java"
stringA = stringA.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
10.字符串遍历
let abc: String = "abc"
for c in abc {
print(c)
}
11.字符串翻转
let abc: String = "abc"
print(String(abc.reversed()))// cba
12.reduce函数
let abc: String = "abc"
let result = abc.reduce("1") { (result, c) -> String in
print(result)
print(c)
return result + String(c)
}
print(result) // 1abc
13.map函数应用
let abc: String = "abc"
let arr = abc.map {
"\($0)" + "-hello"
}
print(arr) // ["a-hello", "b-hello", "c-hello"]
14.filter过滤函数应用
let abc: String = "abcdb"
let filtered = abc.filter { $0 == "b" }
print(filtered) // bb
字符串的翻转,遍历,map函数,reduce函数,filter函数用法与数组类似,猜测应该是遵守了Collection 协议,因此具备这些方法调用的能力
15.Swift4 字符串换行特殊符号"""
- Swift 3 中写很长的字符串只能写在一行,字符串中间有换行只能通过添加 \n 字符来代表换行。
func tellJoke(name: String, character: Character) {
let punchline = name.filter { $0 != character }
let n = name.count - punchline.count
let joke = """
Q: Why does \(name) have \(n) \(character)'s in their name?
A: I don't know, why does \(name) have \(n) \(character)'s in their name?
Q: Because otherwise they'd be called \(punchline).
"""
print(joke)
}
16.One-sided Slicing语法糖 ... 可以对字符串进行单侧边界取子串
let values = "abcdefg"
let startSlicingIndex = values.index(values.startIndex, offsetBy: 3)
let subvalues = values[startSlicingIndex...] // defg
let subvalues2 = values[...startSlicingIndex] // abcd
参考
最全的 Swift 4 新特性解析
Swift - 在字符串中查找另一字符串首次出现的位置(或最后一次出现位置)