-3

It is necessary to remove the quotes at the beginning and end of the line, if they are in the line Could it be more beautiful?

var str = "\"Hello, playground\""
let quotes = "\""

if str.hasPrefix(quotes) && str.hasSuffix(quotes) {
    let v = str.dropFirst()
    str = String(v.dropLast())
}
print(str)
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
Andrey Zet
  • 556
  • 1
  • 5
  • 8

3 Answers3

3

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()                        //
ielyamani
  • 17,807
  • 10
  • 55
  • 90
0

You can use Collection removeFirst and removeLast mutating methods:

var str = "\"Hello, playground\""
let quotes = "\""

if str.hasPrefix(quotes) && str.hasSuffix(quotes) && str != quotes {
    str.removeFirst()
    str.removeLast()
}
print(str)  // "Hello, playground\n"
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
  • 1
    @Sh_Khan I don't know what you mean by one line. It does what OP asked to mutate the original string and remove both ends it the quotes are present. It also makes sure the original string it is not a single quotes character. – Leo Dabus Nov 14 '18 at 20:12
-1

you can do so:

let str = "\"Hello, playground\""

let new = str.filter{$0 != "\""}
flowGlen
  • 627
  • 3
  • 11