Unable to replace string in Swift

人走茶凉 提交于 2021-02-05 06:22:07

问题


Trying to escape few special characters of string for sending it via xml api.

Tried below code but not working for all the occurrences of Single Quote (') and Double Quote (")

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

Result is &quot;Hello” &apos;world’

If anyone can help, thanks!


回答1:


You need to specify replacement strings for and because ’ != ‘ and ” != “

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



回答2:


The reason for this is because is different than and is different than . So you need to add these lines too.

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

This will give you the expected result




回答3:


If you print the ascii values of the string you will see the quotes are not the same unicode character. So make sure you use the same unicode character or handle both case

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



回答4:


Your code is working perfectly fine with me . I just changed the strings as I mentioned in the comments :

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

Just change the letters using the key combination and it will work



来源:https://stackoverflow.com/questions/52873051/unable-to-replace-string-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!