티스토리 뷰

반응형
문자열 접근과 수정
  • 문자열 인덱스
    • 각 String값은 문자열에 각 Character의 위치에 해당하는 String.Index인 인덱스 타입을 가지고 있다.
    • Swift 문자열은 정수값으로 인덱스를 생성할 수  없다.
    • 문자열 범위를 벗어나면 런타임 에러가 발생한다.
let hello = "Hello"
hello[hello.startIndex] // H
hello[hello.index(before: hello.endIndex)] // o
hello[hello.index(after: hello.startIndex)] // e

let index = hello.index(hello.startIndex, offsetBy: 3)
hello[index] // l

 

  • 삽입과 삭제
    • insert(_:at:) // 하나의 문자를 삽입
    • insert(contentsOf:at:) // 다른 문자열의 콘텐츠를 특정 인덱스에 삽입
    • remove(at:) // 하나의 문자를 삭제
    • removeSubrange(_:) // 특정 범위의 부분 문자열을 삭제
var hello = "hello"
hello.insert("😀", at: hello.endIndex)
hello.insert(contentsOf: ", world", at: hello.index(before: hello.endIndex))

hello.remove(at: hello.index(before: hello.endIndex))

let range = hello.index(hello.endIndex, offsetBy: -7)..<hello.endIndex
hello.removeSubrange(range)

 

 

부분 문자열(SubStrings)
  • prefix(_:)와 같은 메서드를 사용하여 부분 문자열을 얻을 때 그 결과는 다른 문자열이 아닌 SubString의 인스턴스이다.
  • 부분 문자열은 문자열과 다르게 문자열에 대한 작업을 수행하는 동안 짧은 시간동안만 부분 문자열을 사용한다.
  • 결과르 저장할 준비가 되었을 때 부분 문자열을 String의 인스턴스로 변환한다.
let greeting = "Hello, world!"
let index = greeting.firstIndex(of: ",") ?? greeting.endIndex
let beginning = greeting[..<index] // Hello

let newString = String(beginning) // 부분 문자열은 장기저장에 적합하지 않다.

 

반응형

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

Swift for문 stride  (0) 2022.08.13
Swift CaseIterable 알아보기  (0) 2022.07.14
Swift final class 알아보기  (0) 2022.06.19
Swift String(문자열) 쉽게 다루기  (0) 2022.06.14
Swift Dictionary  (0) 2022.04.21
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/06   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
글 보관함