简体   繁体   中英

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(")")

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 .

Use your two ranges to create a new range and call replaceRange :

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

a.replaceRange(range!.startIndex...range2!.startIndex, with: "(live version)")
print(a) // Somesong here - Artist (live version)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM