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


当前回答

对于任何想要从字符串中删除前导空格的人(正如问题标题所明确要求的那样),这里有一个答案:

假设:

let string = "   Hello, World!   "

要删除所有前导空格,使用以下代码:

var filtered = ""
var isLeading = true
for character in string {
    if character.isWhitespace && isLeading {
        continue
    } else {
        isLeading = false
        filtered.append(character)
    }
}
print(filtered) // "Hello, World!   "

我相信有比这更好的代码,但它已经完成了我的工作。

其他回答

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

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"

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

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

你也可以试试这个

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

斯威夫特4

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

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

// thisiswrongcontainedteeext

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

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