본문 바로가기
iOS Swift/문법

[Swift] String Index

by 야고이 2024. 2. 20.
728x90

240220_2

startIndex

endIndex

import Foundation

//[String index]
//0부터 시작하는 정수. 특정 데이터의 위치를 나타냄. 문자열에서는 문자의 위치를 나타낼 때 사용

/*
 문자 순서
 Swift
 01234
 54321
 */

let str = "Swift"
str.startIndex //첫번째 문자의 인덱스.

//첫번째 문자 출력
let firstch = str[str.startIndex]
print(firstch)


//마지막 문자 출력
/*
let lastCh = str[str.endIndex]
print(lastCh)
--> 출력 안됨
 
endIndex 는 마지막의 다음이라는 뜻 -> Past the end
마지막 문자를 출력하고 싶으면 endIndex 바로 전의 문자를 출력해야한다
 */

let lastCharaIndex = str.index(before: str.endIndex)
let lastCh = str[lastCharaIndex] // ??str[str.lastCharaIndex] 왜 이렇게 적으면 안돼?
print(lastCh)

//두번째 문자 출력
let secondCharIndex = str.index(after: str.startIndex)
let sencondCh = str[secondCharIndex]
print(sencondCh)

 

offsetBy

//세번째 문자 출력
//위에서 쓴 index를 사용하면 필요이상으로 코드가 길어짐 그럴 땐 offsetBy 사용
var thirdCharIndex = str.index(str.startIndex, offsetBy: 2) //offsetBy는 정수
var thirdCh = str[thirdCharIndex]
print(thirdCh)


//endIndex 와 offsetBy 사용
thirdCharIndex = str.index(str.endIndex, offsetBy: -3) //**endIndex는 마지막 문자의 다음 인덱스다
thirdCh = str[thirdCharIndex]
print(thirdCh)

 

 

/*
 인덱스를 사용할 떄는 올바른 범위를 벗어나지 않는게 중요하다
 인덱스가 올바른 범위를 확실 할 수 없을 때 if 나 gaurd 로 올바른 범위를 확인하는게 좋다
 유니코드 때문에 인덱스를 이따구로 씀
 */

//범위 확인 코드
if thirdCharIndex < str.endIndex && thirdCharIndex >= str.startIndex {
    
}

728x90

'iOS Swift > 문법' 카테고리의 다른 글

[Swift] String Editing #1  (0) 2024.02.21
[Swift] String Basics  (0) 2024.02.21
[Swift] 개념공부 3  (1) 2024.02.20
[Swift] if, guard,switch Statement  (0) 2024.02.19
[Swift] 자료형과 연산자 개념  (0) 2024.02.16

댓글