无法替换Swift中的字符串

Dha*_*ena 2 xml ios double-quotes swift single-quotes

试图通过xml api发送它的几个特殊字符串.

尝试下面的代码但不适用于所有单引号(')和双引号(")的出现

var strToReturn = "“Hello” ‘world’"
strToReturn = strToReturn.replacingOccurrences(of: "&", with: "&")
strToReturn = strToReturn.replacingOccurrences(of: "<", with: "&lt;")
strToReturn = strToReturn.replacingOccurrences(of: ">", with: "&gt;")
strToReturn = strToReturn.replacingOccurrences(of: "‘", with: "&apos;")
strToReturn = strToReturn.replacingOccurrences(of: "“", with: "&quot;") 

print("Replaced string : \(strToReturn)") 
Run Code Online (Sandbox Code Playgroud)

结果是 &quot;Hello” &apos;world’

如果有人可以提供帮助,谢谢!

Kam*_*ran 7

您需要为和指定替换字符串和因为’ != ‘” != “

var strToReturn = "“Hello” ‘world’"
strToReturn = strToReturn.replacingOccurrences(of: "&", with: "&amp;")
strToReturn = strToReturn.replacingOccurrences(of: "<", with: "&lt;")
strToReturn = strToReturn.replacingOccurrences(of: ">", with: "&gt;")
strToReturn = strToReturn.replacingOccurrences(of: "‘", with: "&apos;")
strToReturn = strToReturn.replacingOccurrences(of: "“", with: "&quot;")
strToReturn = strToReturn.replacingOccurrences(of: "’", with: "&apos;")
strToReturn = strToReturn.replacingOccurrences(of: "”", with: "&quot;") 
Run Code Online (Sandbox Code Playgroud)