String

1. 字符串的截取:

extension String {
    
    var length: Int {
        return self.count
    }
    
    subscript (i: Int) -> String {
        return self[i ..< i + 1]
    }
    
    func substring(fromIndex: Int) -> String {
        return self[min(fromIndex, length) ..< length]
    }
    
    func substring(toIndex: Int) -> String {
        return self[0 ..< max(0, toIndex)]
    }
    func toRange(_ range: NSRange) -> Range? {
        guard let from16 = utf16.index(utf16.startIndex, offsetBy: range.location, limitedBy: utf16.endIndex) else { return nil }
        guard let to16 = utf16.index(from16, offsetBy: range.length, limitedBy: utf16.endIndex) else { return nil }
        guard let from = String.Index(from16, within: self) else { return nil }
        guard let to = String.Index(to16, within: self) else { return nil }
        return from ..< to
    }
    
    subscript (r: Range) -> String {
        let range = Range(uncheckedBounds: (lower: max(0, min(length, r.lowerBound)), upper: min(length, max(0, r.upperBound))))
        let start = index(startIndex, offsetBy: range.lowerBound)
        let end = index(start, offsetBy: range.upperBound - range.lowerBound)
        return String(self[start ..< end])
    }  
}

2. 判断是否包含字符(串)

let str = "abcdefg"
print(str.contains("cd"))   //true
print(str.contains("c"))    //true
print(str.contains("o"))    //false

3. 字符串转数组

//字符串拆分(以单个或多个字符为分隔符)
let str = "abcdefg$$aaaa$$bbbb$$ccc"
let des = str.components(separatedBy: "$$")
print(des)  //["abcdefg", "aaaa", "bbbb", "ccc"]

4. 大小写转换

let str = "abcdefg"
print(str.lowercased())  //全部小写
print(str.uppercased())  //全部大写

5. 字符串替换

let str = "abcdefg$$aaaa$$bbbb$$ccc"
let dest11 = str.replacingOccurrences(of: "$$", with: "**")
print(dest11)

6. 查找字符串的位置

let a = "hello world"
let findNum = a.distance(from: a.startIndex, to: (a.range(of: "o")?.lowerBound)!)

你可能感兴趣的:(String)