If you like a one liner:
let str = "\"\"\"Hello, playground\"\""
let unquoted = String(str.drop(while: { $0 == "\""}).reversed().drop(while: { $0 == "\""}).reversed())
print(unquoted) //Hello, playground
You could define these extensions to make it look a tad prettier:
extension String {
private func removeQuotesAndReverse() -> String {
return String(self.drop(while: { $0 == "\""}).reversed())
}
func unquote() -> String {
return self.removeQuotesAndReverse().removeQuotesAndReverse()
}
}
And use it like so:
let unquoted = "\"\"\"Hello, playground\"\"".unquote()
If you only need to remove the first and last quotes, if they are both present, then I would only add a check that the count is at least 2 characters, since a string like "\""
has quotes in both the prefix and suffix, but it's not between quotes:
extension String {
func withoutDoubleQuotes() -> String {
if self.hasPrefix("\""), self.hasSuffix("\""), self.count > 1 {
return String(self.dropFirst().dropLast())
}
return self
}
}
and use it like so:
"\"Hello, playground\"".withoutDoubleQuotes() //Hello, playground
"\"\"\"Hello, playground\"\"".withoutDoubleQuotes() //""Hello, playground"
"\"".withoutDoubleQuotes() //"
"\"\"".withoutDoubleQuotes() //