Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 763
Mahmut Acar Avatar asked Dec 22 '25 21:12

Mahmut Acar


1 Answers

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)
}
like image 161
vadian Avatar answered Dec 24 '25 11:12

vadian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!