ios 无法在Swift中替换字符串

y0u0uwnf  于 2023-05-02  发布在  iOS
关注(0)|答案(5)|浏览(224)

尝试转义字符串的一些特殊字符,以便通过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’
如果有人可以帮助,谢谢!

fcipmucu

fcipmucu1#

您需要为指定替换字符串,因为’ != ‘” != “

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

r7xajy2e2#

这是因为不同于不同于。所以你也需要添加这些行。

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

这会给予你预期的结果

6mw9ycah

6mw9ycah3#

如果你打印字符串的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
sdnqo3pr

sdnqo3pr4#

你的代码和我一起工作得很好。我只是改变了strings,正如我在评论中提到的:
如果有人想知道字符串中的单引号和双引号是如何生成的---按住alt/option并按下方括号/方括号键
只要改变字母使用组合键,它将工作

r6hnlfcb

r6hnlfcb5#

下面扩展非常有用

var toReplaceSmartQuotes: String {
        return self.replacingOccurrences(of: "‘", with: "'").replacingOccurrences(of: "’", with: "'")
            .replaceCharacters(characters: "”", toSeparator: #"""#)
    }
    
    func replaceCharacters(characters: String, toSeparator: String) -> String {
        let characterSet = CharacterSet(charactersIn: characters)
        let components = components(separatedBy: characterSet)
        let result = components.joined(separator: toSeparator)
        return result
    }

相关问题