我需要一种方法来删除字符串的第一个字符,这是一个空格。我正在寻找一个方法,甚至是一个扩展的字符串类型,我可以用来削减字符串的字符。


当前回答

在Swift 4修剪空白

let strFirstName = txtFirstName.text?.trimmingCharacters(in: 
 CharacterSet.whitespaces)

其他回答

当你想要删除所有类型的空白时(基于这个SO答案)的正确方法是:

extension String {
    var stringByRemovingWhitespaces: String {
        let components = componentsSeparatedByCharactersInSet(.whitespaceCharacterSet())
        return components.joinWithSeparator("")
    }
}

Swift 3.0+ (3.0, 3.1, 3.2, 4.0)

extension String {
    func removingWhitespaces() -> String {
        return components(separatedBy: .whitespaces).joined()
    }
}

EDIT

这个答案是在问题是关于删除所有空白时发布的,问题被编辑为只提到前导空白。如果你只想删除前导空白,请使用以下方法:

extension String {
    func removingLeadingSpaces() -> String {
        guard let index = firstIndex(where: { !CharacterSet(charactersIn: String($0)).isSubset(of: .whitespaces) }) else {
            return self
        }
        return String(self[index...])
    }
}

删除字符串中的所有空格:

let space_removed_string = (yourstring?.components(separatedBy: " ").joined(separator: ""))!

Swift 3版本

  //This function trim only white space:
   func trim() -> String
        {
            return self.trimmingCharacters(in: CharacterSet.whitespaces)
        }
    //This function trim whitespeaces and new line that you enter:
     func trimWhiteSpaceAndNewLine() -> String
        {
            return self.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
        }

对我来说,下面这行用来删除空白。

let result = String(yourString.filter {![" ", "\t", "\n"].contains($0)})

斯威夫特4

使用正则表达式的最佳情况:

" this is    wrong contained teee xt     "
    .replacingOccurrences(of: "^\\s+|\\s+|\\s+$", 
                          with: "", 
                          options: .regularExpression)

// thisiswrongcontainedteeext