swift

swift - String Index

행복하게사는게꿈 2021. 1. 6. 18:58

String Index

// 문자열 인덱스
// swift는 정수로 접근하지 않는다.
let str = "Swift"

let firstCh = str[str.startIndex]

// str.endIndex는 마지막 인덱스 다음 인덱스이기 때문에 에러남
// let lastCh = str[str.endIndex]

// 이렇게 가져와야 된다..
let lastCharIndex = str.index(before: str.endIndex)
let lastCh = str[lastCharIndex]

let secondCharIndex = str.index(after: str.startIndex)
let secondCh = str[secondCharIndex]

// 근데 이러면 너무 귀찮잖아..
// var thirdIndex = str.index(after: secondCharIndex)

var thirdCharIndex = str.index(str.startIndex, offsetBy: 2)
var thirdCh = str[thirdCharIndex]

thirdCharIndex = str.index(str.endIndex, offsetBy: -3)
thirdCh = str[thirdCharIndex]


// swift에서 인덱스 가져오는건 생각보다 귀찮네..

// 인덱스 유효성 검사
// 유니코드에 독립적인 형태로 처리하기 때문에 복잡하다
if thirdCharIndex < str.endIndex && thirdCharIndex >= str.startIndex {
    
}