Created
April 7, 2020 18:54
-
-
Save mzeeshanid/ddcf5bddcde4b545bb6651174d8965ec to your computer and use it in GitHub Desktop.
Search for string with before and after limit
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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