Search with prefix and suffix by applying limit in string in Swift

Muhammad Zeeshan
Mac O’Clock
Published in
2 min readApr 7, 2020

Let’s say! you have large text and you would like your user to search through the text but in the search results you don’t want to show the full text. You want to show the prefix and suffix for the searched string with some limit. See the image below for illustration.

Illustration for desired result

So, the first step is to find out the range for the user query in the targeted string for example, text is the user query in the above illustration. Finding the range of substring is pretty simple in swift and it just requires one line of code.

let range = someString.range(of: queryString)

Next step is to determine, how far can we go in the targeted string by considering the provided limit, before and after the query string. See the image below for illustration and code.

Illustration for before and after query string
Code

Explanation

First we need to find the maximum distance we can travel in the backward direction from the range of query string’s lower bound. As we are moving in the backward direction so, we use a -ve sign. In order to avoid the range out of bounds exception we just collected the max value. For example, our limit is -13 in this case and our string ends at -5. Similarly, we need to travel in the forward direction from the range of query string’s upper bound. As we are moving forward so, we use a +ve value. In this case, in order to avoid range out of bounds exception we just collected min value. For example our limit is 13 in this case and our string ends at 5. By using these distance values we can easily find out the start and end index of our desired string. After finding indexes we can easily get the substring.

Sugar coating

In the code above after finding ranges for before and after string I have just added some conditions that will add 3 dots only if needed. That’s it ;)
If you know some other better technique for achieving the same result then don’t hesitate to share it in the comments section below. Thanks!

--

--