관리 메뉴

김종권의 iOS 앱 개발 알아가기

[iOS - swift 공식 문서] 3. String (문자열) 본문

swift 공식 문서

[iOS - swift 공식 문서] 3. String (문자열)

jake-kim 2021. 6. 18. 01:20

문자열 index 접근

  • startIndex와 index(:offsetBy:) 사용
var str = "abc d e f"

// a 가져오는 방법
str.first // 타입: Character?, String.Element
str[str.startIndex] // 타입: Character

// b 가져오는 방법
str[str.index(after: str.startIndex)]

// d 가져오는 방법
str[str.index(str.startIndex, offsetBy: 4)]

특정 문자열 접근

  • firstIndex(of:) 사용
    • 0~특정 index 가져오기
    • 인덱스로 접근하면 타입이 String.SubSequence가 되므로 따로 String 변환이 필요
var str = "abc, def"

// abc 가져오는 방법
let lastIndex = str.firstIndex(of: ",") ?? str.endIndex
let targetSubSequence = str[..<lastIndex] // "abc", 타입: String.SubSequence
let newString = String(targetSubSequence) // "abc"

문자열과 for문

  • .indices
let str = "1234"
for index in str.indices {
    print(str[index])
}

// result
1
2
3
4
  • String.Element 
for stringElement in str {
    print(stringElement)
}

// result
1
2
3
4

문자열 비교

  • == 를 사용
var str = "abc, def"
var str2 = "abc, def"

print(str == str2) // true

hasPrefix(_:), hasSuffix(_:)

var str = "abc, def"

str.hasPrefix("a") // true
str.hasPrefix("bc") // false

str.hasSuffix("def") // true
str.hasSuffix("de") // false

* 참고

https://docs.swift.org/swift-book/LanguageGuide/StringsAndCharacters.html

Comments