3

I have a string and I need to delete following characters

\ " { ] }

from a string. Everything working fine except the double quotation mark.

My string is :

{"fileId":1902,"x":38,"y":97}

after the following operations are performed:

let charsToBeDeleted = CharacterSet(charactersIn: "\"{]}")
let trimmedStr = str.trimmingCharacters(in: charsToBeDeleted)
print(trimmedStr)

prints:

fileId":1902,"x":38,"y":97

It trimmed first double quotation mark but not the other ones. How can I trim this string without double quotation marks?

Mahmut Acar
  • 713
  • 2
  • 7
  • 26

2 Answers2

9

trimmingCharacters(in is the wrong API. It removes characters from the beginning ({") and end (}) of a string but not from within.

What you can do is using replacingOccurrences(of with Regular Expression option.

let trimmedStr = str.replacingOccurrences(of: "[\"{\\]}]", with: "", options: .regularExpression)

[] is the regex equivalent of CharacterSet.
The backslashes are necessary to escape the double quote and treat the closing bracket as literal.


But don't trim. This is a JSON string. Deserialize it to a dictionary

let str = """
{"fileId":1902,"x":38,"y":97}
"""

do {
    let dictionary = try JSONSerialization.jsonObject(with: Data(str.utf8)) as! [String:Int]
    print(dictionary)
} catch {
    print(error)
}

Or even to a struct

struct File : Decodable {
    let fileId, x, y : Int
}

do {
    let result = try JSONDecoder().decode(File.self, from: Data(str.utf8))
    print(result)
} catch {
    print(error)
}
vadian
  • 274,689
  • 30
  • 353
  • 361
2

I haven't test this but it would be something like this:

You may have to check if the escape of characters for \ and " inside the set is used correctly.

let charsToDelete:Set<Character> = ["\\", "\"", "{", "]", "}"]
str.removeAll(where: { charsToDelete.contains($0)})
print(str)
LinusGeffarth
  • 27,197
  • 29
  • 120
  • 174
acarlstein
  • 1,799
  • 2
  • 13
  • 21