Home > AI > Language > Swift >

String+Ext

Example

let str = "abcdef"
        print(str[1 ..< 3]) // returns "bc"
        print(str[5]) // returns "f"
        print(str[80]) // returns ""
        print(str.substring(fromIndex: 3)) // returns "def"
        print(str.substring(toIndex: str.count - 2))// returns "abcd"
extension String {

    subscript (i: Int) -> String {
        return self[i ..< i + 1]
    }

    func substring(fromIndex: Int) -> String {
        return self[min(fromIndex, count) ..< count]
    }

    func substring(toIndex: Int) -> String {
        return self[0 ..< max(0, toIndex)]
    }

    subscript (r: Range<Int>) -> String {
        let range = Range(uncheckedBounds: (lower: max(0, min(count, r.lowerBound)),
                                            upper: min(count, 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])
    }
}

Leave a Reply