无法替换 Swift 中的字符串

Unable to replace string in Swift

正在尝试转义字符串中的几个特殊字符以便通过 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)") 

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

如果有人能帮忙,谢谢!

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

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;") 

这是因为 不同于 不同于 。所以你也需要添加这些行。

strToReturn = strToReturn.replacingOccurrences(of: "’", with: "&apos;")
strToReturn = strToReturn.replacingOccurrences(of: "”", with: "&quot;") 

这会给你预期的结果

你的代码对我来说工作得很好。正如我在评论中提到的那样,我刚刚更改了 strings

For anyone wondering how the Single and Double quotes inside the strings are generated --- Hold down alt/option and press Square / Curly bracket keys

只需使用组合键更改字母即可

如果您打印字符串的 ascii 值,您会看到引号不是同一个 unicode 字符。因此,请确保您使用相同的 unicode 字符或处理两种情况

strToReturn.characters.map{print([=10=], "\(String([=10=].unicodeScalars.first!.value, radix: 16, uppercase: true))")}

“ 201C
H 48
e 65
l 6C
l 6C
o 6F
” 201D
  20
‘ 2018
w 77
o 6F
r 72
l 6C
d 64
’ 2019