🔥 문자열 접근 및 수정하기

387자
5분

Swift에서는 문자열의 메서드와 속성을 사용하거나 서브스크립트 문법을 사용하여 문자열에 접근하고 수정할 수 있습니다. 이번 글에서는 문자열을 다루는 다양한 방법에 대해 알아보겠습니다.

문자열 인덱스

Swift의 String 타입은 각 문자의 위치에 해당하는 연관 인덱스 타입인 String.Index를 가지고 있습니다. 앞서 언급한 것처럼, 서로 다른 문자는 저장하는데 필요한 메모리 크기가 다를 수 있기 때문에, 특정 위치의 문자를 알아내려면 문자열의 시작 또는 끝에서부터 각 유니코드 스칼라를 순회해야 합니다. 이런 이유로 Swift의 문자열은 정수 값으로 인덱싱할 수 없습니다.

문자열의 첫 번째 문자의 위치에 접근하려면 startIndex 속성을 사용하면 됩니다. endIndex 속성은 문자열의 마지막 문자 다음 위치를 나타냅니다. 따라서 endIndex 속성은 문자열의 서브스크립트에 유효한 인자가 아닙니다. 만약 문자열이 비어있다면, startIndexendIndex는 같은 값을 가집니다.

주어진 인덱스의 이전과 이후 인덱스에 접근하려면 Stringindex(before:)index(after:) 메서드를 사용하면 됩니다. 주어진 인덱스에서 더 멀리 떨어진 인덱스에 접근하려면, 이 메서드들을 여러 번 호출하는 대신 index(_:offsetBy:) 메서드를 사용할 수 있습니다.

서브스크립트 문법을 사용하여 특정 문자열 인덱스의 문자에 접근할 수 있습니다.

swift
let greeting = "Guten Tag!"
greeting[greeting.startIndex]
// "G"
greeting[greeting.index(before: greeting.endIndex)]
// "!"
greeting[greeting.index(after: greeting.startIndex)]
// "u"
let index = greeting.index(greeting.startIndex, offsetBy: 7)
greeting[index]
// "a"
swift
let greeting = "Guten Tag!"
greeting[greeting.startIndex]
// "G"
greeting[greeting.index(before: greeting.endIndex)]
// "!"
greeting[greeting.index(after: greeting.startIndex)]
// "u"
let index = greeting.index(greeting.startIndex, offsetBy: 7)
greeting[index]
// "a"

문자열의 범위를 벗어난 인덱스나 문자열의 범위를 벗어난 인덱스의 문자에 접근하려고 하면 런타임 에러가 발생합니다.

swift
greeting[greeting.endIndex] // 에러
greeting.index(after: greeting.endIndex) // 에러
swift
greeting[greeting.endIndex] // 에러
greeting.index(after: greeting.endIndex) // 에러

indices 속성을 사용하여 문자열의 모든 문자 인덱스에 접근할 수 있습니다.

swift
for index in greeting.indices {
    print("\(greeting[index]) ", terminator: "")
}
// "G u t e n   T a g ! "를 출력합니다.
swift
for index in greeting.indices {
    print("\(greeting[index]) ", terminator: "")
}
// "G u t e n   T a g ! "를 출력합니다.

삽입과 제거

지정된 인덱스에 단일 문자를 삽입하려면 insert(_:at:) 메서드를 사용하고, 지정된 인덱스에 다른 문자열의 내용을 삽입하려면 insert(contentsOf:at:) 메서드를 사용합니다.

swift
var welcome = "hello"
welcome.insert("!", at: welcome.endIndex)
// welcome은 이제 "hello!"
 
welcome.insert(contentsOf: " there", at: welcome.index(before: welcome.endIndex))
// welcome은 이제 "hello there!"
swift
var welcome = "hello"
welcome.insert("!", at: welcome.endIndex)
// welcome은 이제 "hello!"
 
welcome.insert(contentsOf: " there", at: welcome.index(before: welcome.endIndex))
// welcome은 이제 "hello there!"

지정된 인덱스에서 단일 문자를 제거하려면 remove(at:) 메서드를 사용하고, 지정된 범위의 부분 문자열을 제거하려면 removeSubrange(_:) 메서드를 사용합니다.

swift
welcome.remove(at: welcome.index(before: welcome.endIndex))
// welcome은 이제 "hello there"
 
let range = welcome.index(welcome.endIndex, offsetBy: -6)..<welcome.endIndex
welcome.removeSubrange(range)
// welcome은 이제 "hello"
swift
welcome.remove(at: welcome.index(before: welcome.endIndex))
// welcome은 이제 "hello there"
 
let range = welcome.index(welcome.endIndex, offsetBy: -6)..<welcome.endIndex
welcome.removeSubrange(range)
// welcome은 이제 "hello"

이렇게 문자열의 메서드와 속성을 활용하여 문자열을 쉽게 다룰 수 있습니다. 서브스크립트 문법과 indices 속성을 사용하면 문자열의 개별 문자에 편리하게 접근할 수 있죠. 또한 insert(_:at:), insert(contentsOf:at:), remove(at:), removeSubrange(_:) 메서드를 사용하여 문자열에 문자를 삽입하거나 제거할 수도 있습니다.

이렇게 Swift에서는 문자열을 다양한 방법으로 접근하고 수정할 수 있습니다. Swift가 제공하는 이런 다양한 기능들을 잘 활용한다면 문자열과 관련된 작업을 훨씬 더 수월하게 처리할 수 있을 거예요. 앞으로도 Swift 문자열을 다룰 때 오늘 배운 내용들을 잘 기억해 두시길 바랍니다!

YouTube 영상

채널 보기
리더 펑터 - 함수도 펑터다! | 프로그래머를 위한 카테고리 이론
class-validator 와 DTO | NestJS 가이드
Zod로 스키마 유효성 검사 구현하기 | NestJS 가이드
Git Worktree로 여러 피처 동시에 개발하기 | AI 코딩 시대의 필수 스킬
NestJS 파이프가 뭔가요? 컨트롤러를 보호하는 방법 | NestJS 가이드
입력을 전처리하는 Functor - Contravariant와 contramap 이해하기 | 프로그래머를 위한 카테고리 이론
Product와 Coproduct가 Bifunctor인 이유 | 프로그래머를 위한 카테고리 이론
C++ 속의 펑터 | 프로그래머를 위한 카테고리 이론