简体   繁体   English

无法替换Swift中的字符串

[英]Unable to replace string in Swift

Trying to escape few special characters of string for sending it via xml api. 试图通过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' 结果是&quot;Hello” &apos;world'

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

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 这将为您提供预期的结果

Your code is working perfectly fine with me . 你的代码对我来说非常好。 I just changed the strings as I mentioned in the comments : 我只是改变了我在评论中提到的strings

For anyone wondering how the Single and Double quotes inside the strings are generated --- Hold down alt/option and press Square / Curly bracket keys 对于任何想知道如何生成字符串中的单引号和双引号的人---按住alt /选项并按下Square / Curly括号键

Just change the letters using the key combination and it will work 只需使用组合键更改字母即可

在此输入图像描述

If you print the ascii values of the string you will see the quotes are not the same unicode character. 如果您打印字符串的ascii值,您将看到引号不是同一个unicode字符。 So make sure you use the same unicode character or handle both case 因此,请确保使用相同的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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM