Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deleting Specific Substrings in Strings [Swift] [duplicate]

Tags:

string

swift

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+?

like image 805
xxmbabanexx Avatar asked Feb 25 '17 22:02

xxmbabanexx


People also ask

How do I remove a specific string from a string in Swift?

Removing the specific character To remove the specific character from a string, we can use the built-in remove() method in Swift. The remove() method takes the character position as an argument and removed it from the string.

How do I remove a particular substring from a string?

The first and most commonly used method to remove/replace any substring is the replace() method of Java String class. The first parameter is the substring to be replaced, and the second parameter is the new substring to replace the first parameter.

How do I remove the last two characters from a string in Swift?

Swift String dropLast() The dropLast() method removes the last character of the string.


2 Answers

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: "")
like image 69
ldindu Avatar answered Oct 21 '22 11:10

ldindu


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])
like image 42
Code Different Avatar answered Oct 21 '22 10:10

Code Different