gpt4 book ai didi

ios - 无法在 Swift 中替换字符串

转载 作者:可可西里 更新时间:2023-10-31 23:56:10 25 4
gpt4 key购买 nike

尝试转义字符串的一些特殊字符以通过 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)")

结果是 "Hello"'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;")

关于ios - 无法在 Swift 中替换字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52873051/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com