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


当前回答

Swift 4、4.2和5

仅从前端和尾部移除空间

let str = "  Akbar Code  "
let trimmedString = str.trimmingCharacters(in: .whitespacesAndNewlines)

从字符串中的每一个地方删除空格

let stringWithSpaces = " The Akbar khan code "
let stringWithoutSpaces = stringWithSpaces.replacingOccurrences(of: " ", with: "")

其他回答

这在swift 5中很管用

var myString = " Kwame Ch ef "
myString = myString.replacingOccurrences(of: " ", with: "")
print(myString)

output: Kwame Chef

羽毛球猫的答案的Swift 3版本

extension String {
    func replace(_ string:String, replacement:String) -> String {
        return self.replacingOccurrences(of: string, with: replacement, options: NSString.CompareOptions.literal, range: nil)
    }

    func removeWhitespace() -> String {
        return self.replace(" ", replacement: "")
    }
}

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

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

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

这个String扩展删除了字符串中的所有空格,而不仅仅是尾随空格…

 extension String {
    func replace(string:String, replacement:String) -> String {
        return self.replacingOccurrences(of: string, with: replacement, options: NSString.CompareOptions.literal, range: nil)
    }

    func removeWhitespace() -> String {
        return self.replace(string: " ", replacement: "")
    }
  }

例子:

let string = "The quick brown dog jumps over the foxy lady."
let result = string.removeWhitespace() // Thequickbrowndogjumpsoverthefoxylady.

如果有人从字符串中删除额外的空格,例如= "这是演示文本,请在单词之间删除额外的空格。"

你可以在Swift 4中使用这个函数。

func removeSpace(_ string: String) -> String{
    var str: String = String(string[string.startIndex])
    for (index,value) in string.enumerated(){
        if index > 0{
            let indexBefore = string.index(before: String.Index.init(encodedOffset: index))
            if value == " " && string[indexBefore] == " "{
            }else{
                str.append(value)
            }
        }
    }
    return str
}

结果是

"This is the demo text remove extra space between the words."