[Swift] String.Index (그리고 Substring) - 문자열 다루기

Bibi·2021년 11월 17일
2

[Swift] String.Index (그리고 Substring) - 문자열 다루기

애플 공식 문서

Swift Standard Library > String > String.Index

https://developer.apple.com/documentation/swift/string/index/

Swift Standard Library > Substring

https://developer.apple.com/documentation/swift/substring

설명과 예제를 참고한 훌륭한 글

http://seorenn.blogspot.com/2018/05/swift-string-index.html

String.Index

문자열에서 문자나 코드 유닛의 위치.

: 스위프트에서 문자열의 인덱스를 표현하기 위해 사용하는 특수한 타입이다.

❗️ 스위프트의 String에서는 인덱스로 정수(Int)를 받지 않는다. 그 대신 String.Index를 사용하는 것이다.

var hello = "hello" 라고 하자.

문자열의 맨 첫 글자 구하기

  • prefix(n) : 앞에서부터 n글자 가져오기
    • let he = hello.prefix(2)
  • startIndex 활용하기
    • let first = hello[hello.startIndex]
  • String.Index(encodedOffset: 0) : 0번째 인덱스를 나타내는 인덱스 생성

문자열의 두 번째 글자 구하기

두 번째 글자를 나타내는 인덱스를 먼저 생성한 뒤, 그 인덱스를 활용해 두 번쨰 글자를 찾는다.

  • let secondIndex = hello.index(after: hello.startIndex)
  • let second = hello[secondIndex]

문자열의 n번째 글자 구하기

func String.index(Substring.Index, offsetBy: Int) -> Substring.Index 를 활용해 구한다.

예를 들어 세 번째 글자 구하기의 경우 아래와 같이 offsetBy를 2 로 설정해 구한다

(인덱스 값은 0부터 시작한다)

  • let thirdIndex = hello.index(hello.startIndex, offsetBy: 2)

문자열의 n번째 이후 모든 글자 구하기

인덱스의 범위 표현 활용.

let s = "12:00:00AM"
let timeIndex = s.index(s.startIndex, offsetBy: 7)
let timeStr = String(s[...timeIndex]) // 12:00:00
let ampmIndex = s.index(s.endIndex, offsetBy: -2)
let ampmStr = String(s[ampmIndex...]) // AM

// 또는 아래와 같이 구할 수도 있다
let timeStr2 = s.prefix(8) // 12:00:00
let ampmStr2 = s.suffix(2) // AM

문자열의 맨 마지막 글자 구하기

  • subfix(n) : 뒤에서부터 n글자 가져오기
    • let lo = hello.suffix(2)
  • endIndexindex(before:) 활용하기
    • endIndex는 문자열의 마지막 글자가 아닌 맨 끝을 가리킨다.
    • hello[hello.endIndex] -> 에러.
    • ⭕️ let endIndex = hello.index(before: hello.endIndex)을 구한 뒤, let last = hello[endIndex] 로 구한다.
  • let endIndex = hello.index(hello.endIndex, offsetBy: -1)
    • 인덱스로부터 왼쪽으로 움직일 때는 offsetBy 값으로 음수를 사용해 준다.

문자열에서 특정 문자의 인덱스 구하기

func firstIndex(of: Character) -> String.Index? 또는

func lastIndex(of: Character) -> String.Index? 를 활용한다.

예를 들어 o라는 문자의 인덱스를 구하려면 아래와 같이 사용한다.

  • let oIndex = hello.index(of: "o")

❗️String.Index 을 구하기 위해 사용한 위의 메서드들은 사실 Substring에서 제공하는 메서드들이다!

문자열 잘라내기

스위프트의 substring = 부분문자열 을 의미한다.

부분문자열은 String.Index를 활용해 범위(range)를 먼저 만들고, 그 범위를 이용해 구한다.

예를 들어 var hello = "hello" 에서 맨 앞, 맨 뒤 글자를 제외한 ell만 구해 보자.

let rangeStartIndex = hello.index(after: hello.startIndex)
let rangeEndIndex = hello.index(hello.index, offsetBy: -2)
let ellSubstring = hello[rangeStartIndex...rangeEndIndex] // Substring 타입의 "ell" 생성

// 아래 코드는 위의 코드와 같은 역할이다.

let rangeStartIndex = hello.index(after: hello.startIndex)
let rangeEndIndex = hello.index(before: hello.endIndex)
let ellSubstring = hello[rangeStartIndex..<rangeEndIndex] // ..< 을 사용함에 주의

인덱스의 범위를 이용해 얻은 부분문자열은 String이 아닌 Substring이라는 별도의 타입이므로, String으로 캐스팅해 주어야 한다.

  • let ellString = String(ellSubstring)

0개의 댓글