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


当前回答

你也可以试试这个

   let updatedString = searchedText?.stringByReplacingOccurrencesOfString(" ", withString: "-")

其他回答

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

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

我会使用这个扩展,以灵活和模仿其他集合如何做到这一点:

extension String {
    func filter(pred: Character -> Bool) -> String {
        var res = String()
        for c in self.characters {
            if pred(c) {
                res.append(c)
            }
        }
        return res
    }
}

"this is a String".filter { $0 != Character(" ") } // "thisisaString"

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

你可以在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 trimmedString = string.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())

Swift 3 / Swift 4:

let trimmedString = string.trimmingCharacters(in: .whitespaces)

你也可以试试这个

   let updatedString = searchedText?.stringByReplacingOccurrencesOfString(" ", withString: "-")