Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift Replace Multiple Characters in String

Below is the following line of code I use to replace an HTML break tag with a carriage return. However, I have other HTML symbols that I need to replace and when I call this line of code again, with different parameters, it's as if the first one is overwritten. Is there a way I can include multiple parameters? Is there a more efficient way to do this in Swift? For example: replace both br> with "" and nbsp with "".

textView.text = content.stringByReplacingOccurrencesOfString("<br /><br />", withString:"\r")
like image 998
Jeff Richard Avatar asked Jan 21 '15 04:01

Jeff Richard


People also ask

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

In the Swift string, we check the removal of a character from the string. To do this task we use the remove() function. This function is used to remove a character from the string. It will return a character that was removed from the given string.

How do I change the last character of a string in Swift?

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

How do I find the length of a string in Swift?

Swift strings can be treated as an array of individual characters. So, to return the length of a string you can use yourString. count to count the number of items in the characters array.


2 Answers

Use replacingOccurrences along with a the String.CompareOptions.regularExpresion option.

Example (Swift 3):

var x = "<Hello, [play^ground+]>"
let y = x.replacingOccurrences(of: "[\\[\\]^+<>]", with: "7", options: .regularExpression, range: nil)
print(y)

Input characters which are to be replaced inside the square brackets like so [\\ Characters]

Output:

7Hello, 7play7ground777
like image 125
Michael Peterson Avatar answered Oct 10 '22 06:10

Michael Peterson


I solved it based on the idea of Rosetta Code

extension String {
    func stringByRemovingAll(characters: [Character]) -> String {
        return String(self.characters.filter({ !characters.contains($0) }))
    }

    func stringByRemovingAll(subStrings: [String]) -> String {
        var resultString = self
        subStrings.map { resultString = resultString.stringByReplacingOccurrencesOfString($0, withString: "") }
        return resultString
    }
}

Example:

let str = "Hello, stackoverflow"
let chars: [Character] = ["a", "e", "i"]
let myStrings = ["Hello", ", ", "overflow"]

let newString = str.stringByRemovingAll(chars)
let anotherString = str.stringByRemovingAll(myStrings)

Result, when printed:

newString: Hllo, stckovrflow

anotherString: stack

like image 22
skofgar Avatar answered Oct 10 '22 07:10

skofgar