Swift Replace Multiple Characters in String

后端 未结 4 514
日久生厌
日久生厌 2021-02-05 13:07

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 lin

相关标签:
4条回答
  • 2021-02-05 13:47
    extension String {
        var html2AttributedString:NSAttributedString {
            return NSAttributedString(data: dataUsingEncoding(NSUTF8StringEncoding)!, options:[NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: NSUTF8StringEncoding], documentAttributes: nil, error: nil)!
        }
    }
    
    let myHtmlCode = "<style type=\"text/css\">#red{color:#F00}#green{color:#0F0}#blue{color: #00F}</style><span id=\"red\" >Red</span> <span id=\"green\" >Green</span><span id=\"blue\">Blue</span>"
    
    myHtmlCode.html2AttributedString
    
    0 讨论(0)
  • 2021-02-05 13:51

    As @matt mentioned you are starting over with the same content string. The stringByReplacingOccurrencesOfString method doesn't actually change anything in the original content string. It returns to you a new string with the replacement changes while content remains unchanged.

    Something like this should work for you

    let result1 = content.stringByReplacingOccurrencesOfString("<br /><br />", withString:"\r") 
    let result2 = result1.stringByReplacingOccurrencesOfString(" &nbsp;", withString:" ")
    textView.text = result2
    
    0 讨论(0)
  • 2021-02-05 13:59

    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
    
    0 讨论(0)
  • 2021-02-05 14:07

    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

    0 讨论(0)
提交回复
热议问题