64

I have a string var m = "I random don't like confusing random code." I want to delete all instances of the substring random within string m, returning string parsed with the deletions completed.

The end result would be: parsed = "I don't like confusing code."

How would I go about doing this in Swift 3.0+?

Hamish
  • 78,605
  • 19
  • 187
  • 280
xxmbabanexx
  • 8,256
  • 16
  • 40
  • 60
  • var m = "I random don't like confusing random code." let parsed = m.replacingOccurrences(of: "random", with: "") print(parsed). // I don't like confusing code. – Jaykant Sep 30 '22 at 17:27

2 Answers2

149

It is quite simple enough, there is one of many ways where you can replace the string "random" with empty string

let parsed = m.replacingOccurrences(of: "random", with: "")
ldindu
  • 4,270
  • 2
  • 20
  • 24
13

Depend on how complex you want the replacement to be (remove/keep punctuation marks after random). If you want to remove random and optionally the space behind it:

var m = "I random don't like confusing random code."
m = m.replacingOccurrences(of: "random ?", with: "", options: [.caseInsensitive, .regularExpression])
Code Different
  • 90,614
  • 16
  • 144
  • 163