swifttrimcharacter-trimming

Trim double quotation mark(") from a string


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?


Solution

  • 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)
    }