Question: I'm trying to make a function in string that deletes some characters from a provided string.

For example i have 

```
"‌Boll %b‌ (Teeth ‌Alligator‌ (13,8,8,5,5,3,n),20,2,ma)"

```

and i want to edit this to

```
"‌Boll %b‌"

```

which means to delete everything between the `"("` and `")"`

So i've made this function

```
func deleteInnerString(with string: String, from firstCharacter: String, to secondCharacter: String) -> String {
    guard let leftIndex = (string.range(of: firstCharacter)?.lowerBound),
        let rightIndex = string.range(of: secondCharacter)?.lowerBound else {
            return string
    }
    let remainingString = String(string.prefix(upTo: leftIndex) + string.suffix(from: string.index(after: rightIndex)))
    return remainingString
}

```

but in this case the output string is

```
"‌Boll %b‌ ,20,2,ma)"

```

The question is, how can i scan the string to find the last closing parenthesis range??

Answer: 
Please note that your strategy won't work with non nested parenthesis.

E.g. this input

```
a(b)c(d)e

```

With your approach will produce this output

```
ae

```

Which IMHO is not correct.

Solution
--------

This solution instead will work with **nested** and **non nested** parenthesis

```
let text = "‌a(b)c(d)e"
var numOfNestedParentesis = 0
var indexesToRemove:Set<Int> = []

for (index, char) in text.enumerated() {

    if char == "(" {
        numOfNestedParentesis += 1
    }

    if numOfNestedParentesis > 0 {
        indexesToRemove.insert(index)
    }

    if char == ")" {
        numOfNestedParentesis -= 1
    }
}

let result = String(text.enumerated()
    .filter { !indexesToRemove.contains($0.offset) }
    .map { $0.element } )

```

Test
----

```
print(result) // ‌ace

```
You have to use `.backwards` option for `String.CompareOptions` in `range` function of string. as like below

```
func deleteString(with string: String, from firstCharacter: String, to secondCharacter: String) -> String {
    guard let leftIndex = (string.range(of: firstCharacter)?.lowerBound),
        let rightIndex = string.range(of: secondCharacter, options: .backwards)?.lowerBound else {
            return string
    }
    let remainingString = String(string.prefix(upTo: leftIndex) + string.suffix(from: string.index(after: rightIndex)))

    return remainingString.trimmingCharacters(in: .whitespaces)
}

```