Swift 敏捷的如何删除字符串开头和结尾的字符?

Swift 敏捷的如何删除字符串开头和结尾的字符?,swift,string,Swift,String,如果行中有引号,则必须删除行首和行尾的引号 它会更漂亮吗 var str = "\"Hello, playground\"" let quotes = "\"" if str.hasPrefix(quotes) && str.hasSuffix(quotes) { let v = str.dropFirst() str = String(v.dropLast()) } print(str) 您可以使用Collection removeFirst和removeL

如果行中有引号,则必须删除行首和行尾的引号 它会更漂亮吗

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

if str.hasPrefix(quotes) && str.hasSuffix(quotes) {
    let v = str.dropFirst()
    str = String(v.dropLast())
}
print(str)

您可以使用Collection removeFirst和removeLast变异方法:

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

if str.hasPrefix(quotes) && str.hasSuffix(quotes) && str != quotes {
    str.removeFirst()
    str.removeLast()
}
print(str)  // "Hello, playground\n"

如果您喜欢单班轮:

let str = "\"\"\"Hello, playground\"\""
let unquoted = String(str.drop(while: { $0 == "\""}).reversed().drop(while: { $0 == "\""}).reversed())
print(unquoted)  //Hello, playground

您可以定义这些扩展,使其看起来更漂亮:

extension String {
    private func removeQuotesAndReverse() -> String {
        return String(self.drop(while: { $0 == "\""}).reversed())
    }
    func unquote() -> String {
        return self.removeQuotesAndReverse().removeQuotesAndReverse()
    }
}
并像这样使用它:

let unquoted = "\"\"\"Hello, playground\"\"".unquote()
"\"Hello, playground\"".withoutDoubleQuotes()       //Hello, playground
"\"\"\"Hello, playground\"\"".withoutDoubleQuotes() //""Hello, playground"
"\"".withoutDoubleQuotes()                          //"
"\"\"".withoutDoubleQuotes()                        //

如果您只需要删除第一个引号和最后一个引号,如果它们都存在,那么我将只添加一个检查,以确保计数至少为2个字符,因为像
“\”
这样的字符串在前缀和后缀中都有引号,但它不在引号之间:

extension String {
    func withoutDoubleQuotes() -> String {
        if self.hasPrefix("\""), self.hasSuffix("\""), self.count > 1 {
            return String(self.dropFirst().dropLast())
        }
        return self
    }
}
并像这样使用它:

let unquoted = "\"\"\"Hello, playground\"\"".unquote()
"\"Hello, playground\"".withoutDoubleQuotes()       //Hello, playground
"\"\"\"Hello, playground\"\"".withoutDoubleQuotes() //""Hello, playground"
"\"".withoutDoubleQuotes()                          //"
"\"\"".withoutDoubleQuotes()                        //
你可以这样做:

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

let new = str.filter{$0 != "\""}

@Sh_Khan我不知道你所说的一行是什么意思。它按照OP的要求对原始字符串进行变异,并在有引号的情况下删除两端。它还确保原始字符串不是一个单引号字符。很漂亮!但是第二个引号也被删除了。@AndreyZet你的意思是只想删除第一个引号吗?delete first和last如果两者都存在,则我已将答案更新为仅考虑第一个和最后一个引号这将删除字符串中的所有引号,而不仅仅是第一个和最后一个引号。