Replace string

1

How can I replace this string with another regardless of whether the value is 2 or 4 or 5

<font size=\"2\"

Now I have it like this:

replacingOccurrences(of: "font size=\"2\"", with: "font size=\"4\"")

But a 2 will not always come by default.

    
asked by Alejandro 18.04.2017 в 10:44
source

1 answer

1

The truth is quite strange the handling of chains in Swift. However, a StackOverflow response in English has helped me much. The general idea is the following (for version 3 of the language):

var cadena = "<font size=\"2\""

let inicio = cadena.index(cadena.endIndex, offsetBy: -2)

Chains have two indexes, initially called startIndex and end called endIndex . From them, we can build intermediate indexes using the methods index

To obtain the index where the number starts in your chain, we obtain the final index and we subtract 2 from it, this we do using the parameter offsetBy that can be positive (which means that we move "to the right" ) or negative (towards "the left")

let fin = cadena.endIndex
let rango = inicio..<fin

We create a range using the operator ..< , which results in a unique range. The ... operator can also be used for an inclusive one

cadena.replacingCharacters(in: rango, with: "nuevo")

which returns: "<font size="nuevo"

The complete code looks like this:

import Foundation

var cadena = "<font size=\"2\""
let inicio = cadena.index(cadena.endIndex, offsetBy: -2)
let fin = cadena.endIndex
let rango = inicio..<fin

cadena.replacingCharacters(in: rango, with: "nuevo")
    
answered by 12.05.2017 / 23:35
source