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


当前回答

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

你可以在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."

其他回答

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

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

羽毛球猫的答案的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: "")
    }
}

对于swift 3.0

import Foundation

var str = " Hear me calling"

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

str.stringByRemovingWhitespaces  // Hearmecalling
extension String {

    var removingWhitespaceAndNewLines: String {
        return removing(.whitespacesAndNewlines)
    }

    func removing(_ forbiddenCharacters: CharacterSet) -> String {
        return String(unicodeScalars.filter({ !forbiddenCharacters.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)
        }