본문 바로가기

# 02/Swift

[Swift] substring

반응형
let s = "hello"
String(Array(s)[0..<3]) // "hel"
s.suffix(4) // "ello"
s.prefix(4) // "hell"


extension String {
    subscript(_ range: CountableRange<Int>) -> String {
        let start = index(startIndex, offsetBy: max(0, range.lowerBound))
        let end = index(start, offsetBy: min(self.count - range.lowerBound, 
                                             range.upperBound - range.lowerBound))
        return String(self[start..<end])
    }

    subscript(_ range: CountablePartialRangeFrom<Int>) -> String {
        let start = index(startIndex, offsetBy: max(0, range.lowerBound))
         return String(self[start...])
    }
}

let s = "hello"
s[0..<3] // "hel"
s[3...]  // "lo"

extension String {
    func index(from: Int) -> Index {
        return self.index(startIndex, offsetBy: from)
    }

    func substring(from: Int) -> String {
        let fromIndex = index(from: from)
        return String(self[fromIndex...])
    }

    func substring(to: Int) -> String {
        let toIndex = index(from: to)
        return String(self[..<toIndex])
    }

    func substring(with r: Range<Int>) -> String {
        let startIndex = index(from: r.lowerBound)
        let endIndex = index(from: r.upperBound)
        return String(self[startIndex..<endIndex])
    }
}

 

반응형

'# 02 > Swift' 카테고리의 다른 글

[Swift] MinHeap  (0) 2022.12.12
[Swift] Factorial / Permutations / Combinations  (0) 2022.12.05
[Swift] 최대공약수, 최소공배수  (0) 2022.11.23
[Swift] 소수 판별  (0) 2022.11.23
[Swift] Dictionary  (0) 2022.11.20