Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- tableView
- 리팩토링
- Clean Code
- clean architecture
- combine
- ribs
- RxCocoa
- uitableview
- rxswift
- map
- 애니메이션
- 리펙토링
- swift documentation
- uiscrollview
- MVVM
- collectionview
- Xcode
- swiftUI
- HIG
- SWIFT
- Human interface guide
- 리펙터링
- Protocol
- 스위프트
- UICollectionView
- Refactoring
- Observable
- UITextView
- 클린 코드
- ios
Archives
- Today
- Total
김종권의 iOS 앱 개발 알아가기
[swift - algorithm] 문자열 자르기, substring 본문
swift의 String 형 value type 특성
- c, c++, java와는 다르게 string형에서 인덱스에 Int로 접근 불가
- swift에서는 인덱스 값에 Int가 아닌 Index자료형이 위치 (swift는 Sring이 reference type이 아닌 value type이기 때문)
let str = "1234"
str[str.startIndex ..< str.endIndex] // 1234
- Index값의 주의 사항: 위처럼 endIndex 값은 문자열 마지막이 아닌, 마지막 다음 문자열의 끝을 참조
String.Index 타입
- Index타입이 따로 존재하며, 이것을 통해 문자열의 위치를 계산
- String은 기본적으로 `self.startIndex`를 제공하므로 startIndex기준으로 떨어진 길이 (offsetBy) int값을 이용하여 Index값 획득
let strSample = "abcdef"
print(strSample.index(strSample.startIndex, offsetBy: 0)) // Index(_rawBits: 1)
substring 구현
- substring의 input, output
// substring 예상 결과
let str = "0123456789"
print(str.substring(from: 2, to: 3)) // 23
- 구현 - 범위 값 체크
extension String {
func substring(from: Int, to: Int) -> String {
guard from < count, to >= 0, to - from >= 0 else {
return ""
}
// Index 값 구하고 파싱
}
}
- 구현 - Index값 획득
extension String {
func substring(from: Int, to: Int) -> String {
guard from < count, to >= 0, to - from >= 0 else {
return ""
}
// Index 값 획득
let startIndex = index(self.startIndex, offsetBy: from)
let endIndex = index(self.endIndex, offsetBy: to)
// 파싱
}
}
- 구현 - 파싱
extension String {
func substring(from: Int, to: Int) -> String {
guard from < count, to >= 0, to - from >= 0 else {
return ""
}
// Index 값 획득
let startIndex = index(self.startIndex, offsetBy: from)
let endIndex = index(self.startIndex, offsetBy: to + 1) // '+1'이 있는 이유: endIndex는 문자열의 마지막 그 다음을 가리키기 때문
// 파싱
return String(self[startIndex ..< endIndex])
}
}
'알고리즘 > 문자열 처리' 카테고리의 다른 글
Comments