无法在Swift中替换字符串

时间:2018-10-18 11:35:38

标签: ios swift xml double-quotes 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)") 

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

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

4 个答案:

答案 0 :(得分: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;") 

答案 1 :(得分:2)

其原因是因为不同,并且不同。因此,您也需要添加这些行。

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

这将为您带来预期的结果

答案 2 :(得分:1)

您的代码对我来说很好用。我刚刚按照评论中的说明更改了strings

  

对于想知道如何在字符串内生成单引号和双引号的任何人---按住alt / option并按方括号/花括号键

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

enter image description here

答案 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