迅速。如何删除字符串开头和结尾的字符?

时间:2018-11-14 19:42:46

标签: 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)

3 个答案:

答案 0 :(得分:1)

如果您喜欢一个班轮:

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()

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

extension String {
    func withoutDoubleQuotes() -> String {
        if self.hasPrefix("\""), self.hasSuffix("\""), self.count > 1 {
            return String(self.dropFirst().dropLast())
        }
        return self
    }
}

并像这样使用它:

"\"Hello, playground\"".withoutDoubleQuotes()       //Hello, playground
"\"\"\"Hello, playground\"\"".withoutDoubleQuotes() //""Hello, playground"
"\"".withoutDoubleQuotes()                          //"
"\"\"".withoutDoubleQuotes()                        //

答案 1 :(得分:0)

您可以使用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"

答案 2 :(得分:-1)

您可以这样做:

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

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