[Swift] Range<String.Index> 의 upperBound 에 대하여

원하는 키워드가 등장하는 첫번째 위치를 중심으로 문자열을 분리해보자

들어가기 전에

let originalText = "서울특별시"
let highlightText = "특별"
let range = originalText.firstRange(of: highlightText)!
range.lowerBound
range.upperBound
originalText.prefix(through: range.lowerBound)
originalText.prefix(through: range.upperBound)
let originalText = "서울특별시"
let highlightText = "특별"
let range = originalText.firstRange(of: highlightText)!
let startIndex = originalText.distance(from: originalText.startIndex,
to: range.lowerBound)
let endIndex = originalText.distance(from: originalText.startIndex,
to: range.upperBound)
print(startIndex, endIndex) // 2 4

Range

lowerBound..<upperBound

마무리

let originalText = "서울특별시"
let highlightText = "특별"
let range = originalText.firstRange(of: highlightText)!
let highlightTextPrefix = String(originalText.prefix(upTo: range.lowerBound))
let highlightTextSuffix = String(originalText.suffix(from: range.upperBound))
print(highlightTextPrefix) //서울
print(highlightText) //특별
print(highlightTextSuffix) //시

참고

--

--

 https://github.com/sujinnaljin/TIL

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store