问题
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: "<")
strToReturn = strToReturn.replacingOccurrences(of: ">", with: ">")
strToReturn = strToReturn.replacingOccurrences(of: "‘", with: "'")
strToReturn = strToReturn.replacingOccurrences(of: "“", with: """)
print("Replaced string : \(strToReturn)")
Result is "Hello” '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: "&")
strToReturn = strToReturn.replacingOccurrences(of: "<", with: "<")
strToReturn = strToReturn.replacingOccurrences(of: ">", with: ">")
strToReturn = strToReturn.replacingOccurrences(of: "‘", with: "'")
strToReturn = strToReturn.replacingOccurrences(of: "“", with: """)
strToReturn = strToReturn.replacingOccurrences(of: "’", with: "'")
strToReturn = strToReturn.replacingOccurrences(of: "”", with: """)
回答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: "'")
strToReturn = strToReturn.replacingOccurrences(of: "”", with: """)
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