Skip to content

Instantly share code, notes, and snippets.

@mzeeshanid
Created April 7, 2020 18:54
Show Gist options
  • Save mzeeshanid/ddcf5bddcde4b545bb6651174d8965ec to your computer and use it in GitHub Desktop.
Save mzeeshanid/ddcf5bddcde4b545bb6651174d8965ec to your computer and use it in GitHub Desktop.
Search for string with before and after limit
let limit = 13
let queryString = "text"
let targettedString = "Lorem Ipsum is simply dummy text of the printing and typesetting"
let queryRange = targettedString.range(of: queryString)
let distanceToStart = max(self.distance(from: queryRange.lowerBound, to: self.startIndex), -limit)
let distanceToEnd = min(self.distance(from: queryRange.upperBound, to: self.endIndex), limit)
let start = self.index(queryRange.lowerBound, offsetBy: distanceToStart)
let end = self.index(queryRange.upperBound, offsetBy: distanceToEnd)
var result = ""
if start != self.startIndex {
result.append("...")
}
result.append(contentsOf: self[start..<end])
if end != self.endIndex {
result.append("...")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment