관리 메뉴

김종권의 iOS 앱 개발 알아가기

[swift - algorithm] 문자열 자르기, substring 본문

알고리즘/문자열 처리

[swift - algorithm] 문자열 자르기, substring

jake-kim 2021. 3. 14. 02:59

swift의 String 형 value type 특성

  • c, c++, java와는 다르게 string형에서 인덱스에 Int로 접근 불가

  • swift에서는 인덱스 값에 Int가 아닌 Index자료형이 위치 (swift는 Sring이 reference type이 아닌 value type이기 때문)
let str = "1234"
str[str.startIndex ..< str.endIndex] // 1234
  • Index값의 주의 사항: 위처럼 endIndex 값은 문자열 마지막이 아닌, 마지막 다음 문자열의 끝을 참조

String.Index 타입

  • Index타입이 따로 존재하며, 이것을 통해 문자열의 위치를 계산
  • String은 기본적으로 `self.startIndex`를 제공하므로 startIndex기준으로 떨어진 길이 (offsetBy) int값을 이용하여 Index값 획득
let strSample = "abcdef"
print(strSample.index(strSample.startIndex, offsetBy: 0)) // Index(_rawBits: 1)

substring 구현

  • substring의 input, output
// substring 예상 결과

let str = "0123456789"
print(str.substring(from: 2, to: 3)) // 23
  • 구현 - 범위 값 체크
extension String {
    func substring(from: Int, to: Int) -> String {
        guard from < count, to >= 0, to - from >= 0 else {
            return ""
        }
        
        // Index 값 구하고 파싱
    }
}
  • 구현 - Index값 획득
extension String {
    func substring(from: Int, to: Int) -> String {
        guard from < count, to >= 0, to - from >= 0 else {
            return ""
        }
        
        // Index 값 획득
        let startIndex = index(self.startIndex, offsetBy: from)
        let endIndex = index(self.endIndex, offsetBy: to)
        
        // 파싱
    }
}
  • 구현 - 파싱
extension String {
    func substring(from: Int, to: Int) -> String {
        guard from < count, to >= 0, to - from >= 0 else {
            return ""
        }
        
        // Index 값 획득
        let startIndex = index(self.startIndex, offsetBy: from)
        let endIndex = index(self.startIndex, offsetBy: to + 1) // '+1'이 있는 이유: endIndex는 문자열의 마지막 그 다음을 가리키기 때문
        
        // 파싱
        return String(self[startIndex ..< endIndex])
    }
}
Comments