Terrance Terrance - 6 months ago 11
Swift Question

Replace from index of one character to the end of another

I wish to replace a string starting from an index of one character to the end of another character. Example replace all characters from index of

(
to index of
)
in the string
Somesong here - Artist (radio edit)
or even if the string is
Somesong here - Artist (radio edit) (another one)
. Any help will be greatly appreciated.

I've tried this but I dont think I'll work out, I not too sure how to remove substring starting at a range.

var a = "Somesong here - Artist (radio edit)"
let range = a.rangeOfString("(")
let range2 = a.rangeOfString(")")

Answer

You could do it like this to use the - range:

 var str = "Somesong here - Artist (radio edit)"
 if let range = str.rangeOfString("-") {
     // str = Somesong here
     str.removeRange(range.startIndex..<str.endIndex)
 }

// str = Somesong here - New Artist
str += "- New Artist"

If you want to use the ( range instead:

var str = "Somesong here - Artist (radio edit)"
if let range = str.rangeOfString("(") {
// str = Somesong here - Artist 
    str.removeRange(range.startIndex..<str.endIndex)
}

// str = Somesong here - Artist (not a radio edit)
str += "(not a radio edit)"

You can ofcourse add the str += ... withing the if let.

Comments