How to insert a substring before/after another substring?

Let’s say we have the string "asd as asdsd", I need to insert "<*>" before and after "asd", so the result should be: "<*>asd<*> as <*>asd<*>sd".

The insertion should be caseInsensitive, so if the target is "ASD" the result is the same: "<*>asd<*> as <*>asd<*>sd"

I tried

a.insert(contentsOf: separator, at: a.range(of: "asd", options: .caseInsensitive)!.upperBound) a.insert(contentsOf: separator, at: a.range(of: "asd", options: .caseInsensitive)!.lowerBound) 

but the separator is only inserted for the first occurrence of "asd"

Add Comment
1 Answer(s)

Note: This solution was posted before OP mentioned a caseInsensitive requirement. A comment by Larme actually included such a solution:

replacingOccurrences(of: "asd", with: "<*>$0<*>", options: [.caseInsensitive, .regularExpression]) 

If he posts this as an answer feel free to accept it.


Here is a possible solution:

extension String {     func enclosing(_ match: String, in tag: String) -> String {         self.replacingOccurrences(of: match, with: tag + match + tag)     } }  let text = "asd as asdsd" print(text.enclosing("asd", in: "<*>"))  // Outputs: <*>asd<*> as <*>asd<*>sd 
Answered on August 31, 2020.
Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.