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


当前回答

如果你想要从前面(和后面)而不是中间删除空格,你应该使用stringByTrimmingCharactersInSet

    let dirtyString   = " First Word "
    let cleanString = dirtyString.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())

如果你想从字符串的任何地方删除空格,那么你可能需要查看stringbyreplacement…

其他回答

尝试函数式编程来删除空白:

extension String {
  func whiteSpacesRemoved() -> String {
    return self.filter { $0 != Character(" ") }
  }
}
string = string.filter ({!" ".contains($0) })

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

对于swift 3.0

import Foundation

var str = " Hear me calling"

extension String {
    var stringByRemovingWhitespaces: String {
        return components(separatedBy: .whitespaces).joined()
    }
}

str.stringByRemovingWhitespaces  // Hearmecalling

从技术上讲,这不是对原始问题的回答,但由于这里的许多帖子都给出了删除所有空白的答案,这里是一个更新的、更简洁的版本:

let stringWithouTAnyWhitespace = string.filter {!$0.isWhitespace}