我需要一种方法来删除字符串的第一个字符,这是一个空格。我正在寻找一个方法,甚至是一个扩展的字符串类型,我可以用来削减字符串的字符。
当前回答
在Swift 4修剪空白
let strFirstName = txtFirstName.text?.trimmingCharacters(in:
CharacterSet.whitespaces)
其他回答
好吧,这是老问题了,但我自己也遇到过这个问题,除了删除所有空白之外,上面的答案都不起作用,这可能会损害应用的功能。我的问题是这样的:
["This", " is", " my", " array", " it is awesome"]
如果修剪所有的空白,这将是输出:
["This", "is", "my", "array", "itisawesome"]
所以我需要消除前导间距,并简单地从:
let array = jsonData.components(separatedBy: ",")
To
let array = jsonData.components(separatedBy: ", ")
修正了这个问题。希望将来有人发现这个有用。
我会使用这个扩展,以灵活和模仿其他集合如何做到这一点:
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 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)
}
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: "")
从技术上讲,这不是对原始问题的回答,但由于这里的许多帖子都给出了删除所有空白的答案,这里是一个更新的、更简洁的版本:
let stringWithouTAnyWhitespace = string.filter {!$0.isWhitespace}