无法在Swift中替换字符串 [英] Unable to replace string in Swift

查看:68
本文介绍了无法在Swift中替换字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试转义一些特殊的字符串以通过xml API发送字符串.

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

结果为&"Hello"& quotaworld

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

If anyone can help, thanks!

推荐答案

您需要为'" 指定替换字符串,因为'!='"!="

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

这篇关于无法在Swift中替换字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆