1

I have a string in the form "this is my title {{and this is what I have to replace}}".

The best way I found so far is:

    let from = originalTitle.firstIndex(of: "{{") ?? 0
    let to = originalTitle.firstIndex(of: "}}") ?? 0

    if let textToReplace = originalTitle.slicing(from: from, to: to), !textToReplace.isEmpty {
        return originalTitle.replacing(textToReplace, with: "XY")
    }

    return originalTitle

However I feel there has to be a better way to explicitly indicate two placeholders or markers and then replace whats inside. Any thoughts?

Thanks in advance!

Andres C
  • 463
  • 6
  • 26
  • Where do the `firstIndex(of:)` and `slicing(from:to:)` methods come from? – Martin R Jun 16 '17 at 16:50
  • 1
    Possible dupes: [Replace string between characters in swift](https://stackoverflow.com/q/42487871/2415822), [Swift Get string between 2 strings in a string](https://stackoverflow.com/q/31725424/2415822), [Swift - Finding a substring between two locations in a string](https://stackoverflow.com/q/27332992/2415822). Have you reviewed those? – JAL Jun 16 '17 at 16:53
  • Do want to replace *all* occurrences of `{{...}}` or only a single one? Are the delimiters fixed or variable? – Martin R Jun 16 '17 at 17:00
  • @JAL best solutions provided there, and some other similars I checked, where regexs. I'm trying to stay clear of those, as this is an exercise to be explained to students – Andres C Jun 19 '17 at 12:42
  • @MartinR There may be N occurrences, and the delimiters are always those – Andres C Jun 19 '17 at 12:43
  • And the replacement text is the same for all occurrences of `{{...}}`? – Martin R Jun 19 '17 at 12:51
  • Nope, not necessarily – Andres C Jun 19 '17 at 13:14
  • So what exactly are the input parameters? The original title and a list of replacement strings? – Martin R Jun 19 '17 at 13:40
  • There is a text that may contain 0, 1 or N occurrences of "{{...}}". Inside the braces there may be any content, assume it is keys; but each key is not important as the replacement will take place on an order basis (first occurrence of placeholder replaced with ABC, second with DEF, etc). The replacement texts come from other place, so it's not important either if those are ABC or 123 at the moment. – Andres C Jun 19 '17 at 13:43

1 Answers1

1

A better possibility so far:

    if let from = originalTitle.range(of: "{{")?.lowerBound, let to = originalTitle.range(of: "}}")?.upperBound {
        let range = from..<to
        return originalTitle.replacingCharacters(in: range, with: "XY")
    }
    return originalTitle
Andres C
  • 463
  • 6
  • 26