0

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

2 Answers 2

0

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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) 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.