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


当前回答

好吧,这是老问题了,但我自己也遇到过这个问题,除了删除所有空白之外,上面的答案都不起作用,这可能会损害应用的功能。我的问题是这样的:

["This", " is", " my", " array", " it is awesome"]

如果修剪所有的空白,这将是输出:

["This", "is", "my", "array", "itisawesome"]

所以我需要消除前导间距,并简单地从:

 let array = jsonData.components(separatedBy: ",")

To

let array = jsonData.components(separatedBy: ", ")

修正了这个问题。希望将来有人发现这个有用。

其他回答

删除开头和结尾的空格:

let trimmedString = string.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())

Swift 3 / Swift 4:

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

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

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

代码少做多。

"Hello World".filter({$0 != " "}) // HelloWorld

你也可以试试这个

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

嗨,这可能有点晚,但值得一试。这是一个游乐场的文件。你可以让它成为一个字符串扩展名。

这是在Swift 5.3中编写的

方法1:

var str = "\n \tHello, playground       "
if let regexp = try? NSRegularExpression(pattern: "^\\s+", options: NSRegularExpression.Options.caseInsensitive) {
    let mstr = NSMutableString(string: str)
    regexp.replaceMatches(in: mstr, options: [], range: NSRange(location: 0, length: str.count), withTemplate: "")
    str = mstr as String
}

Result: "Hello, playground       "

方法2:

if let c = (str.first { !($0 == " " || $0 == "\t" || $0 == "\n") }) {
    if let nonWhiteSpaceIndex = str.firstIndex(of: c) {
        str.replaceSubrange(str.startIndex ..< nonWhiteSpaceIndex, with: "")
    }
}

Result: "Hello, playground       "