尝试转义一些特殊的字符串以通过xml API发送字符串。
尝试以下代码,但不适用于所有出现的单引号(')和双引号(“)
var strToReturn = "“Hello” ‘world’"
strToReturn = strToReturn.replacingOccurrences(of: "&", with: "&")
strToReturn = strToReturn.replacingOccurrences(of: "<", with: "<")
strToReturn = strToReturn.replacingOccurrences(of: ">", with: ">")
strToReturn = strToReturn.replacingOccurrences(of: "‘", with: "'")
strToReturn = strToReturn.replacingOccurrences(of: "“", with: """)
print("Replaced string : \(strToReturn)")
结果为"Hello” 'world’
如果有人可以帮助,谢谢!
答案 0 :(得分:7)
您需要为’
和”
指定替换字符串,因为’ != ‘
和” != “
var strToReturn = "“Hello” ‘world’"
strToReturn = strToReturn.replacingOccurrences(of: "&", with: "&")
strToReturn = strToReturn.replacingOccurrences(of: "<", with: "<")
strToReturn = strToReturn.replacingOccurrences(of: ">", with: ">")
strToReturn = strToReturn.replacingOccurrences(of: "‘", with: "'")
strToReturn = strToReturn.replacingOccurrences(of: "“", with: """)
strToReturn = strToReturn.replacingOccurrences(of: "’", with: "'")
strToReturn = strToReturn.replacingOccurrences(of: "”", with: """)
答案 1 :(得分:2)
其原因是因为”
与“
不同,并且’
与‘
不同。因此,您也需要添加这些行。
strToReturn = strToReturn.replacingOccurrences(of: "’", with: "'")
strToReturn = strToReturn.replacingOccurrences(of: "”", with: """)
这将为您带来预期的结果
答案 2 :(得分:1)
您的代码对我来说很好用。我刚刚按照评论中的说明更改了strings
:
对于想知道如何在字符串内生成单引号和双引号的任何人---按住alt / option并按方括号/花括号键
只需使用组合键更改字母即可使用
答案 3 :(得分:1)
如果打印字符串的ascii值,则会看到引号不是相同的unicode字符。因此,请确保您使用相同的Unicode字符或同时处理两种情况
strToReturn.characters.map{print($0, "\(String($0.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