我需要一种方法来删除字符串的第一个字符,这是一个空格。我正在寻找一个方法,甚至是一个扩展的字符串类型,我可以用来削减字符串的字符。
当前回答
好吧,这是老问题了,但我自己也遇到过这个问题,除了删除所有空白之外,上面的答案都不起作用,这可能会损害应用的功能。我的问题是这样的:
["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 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 "
如果有人从字符串中删除额外的空格,例如= "这是演示文本,请在单词之间删除额外的空格。"
你可以在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."
代码少做多。
"Hello World".filter({$0 != " "}) // HelloWorld
删除开头和结尾的空格:
let trimmedString = string.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
Swift 3 / Swift 4:
let trimmedString = string.trimmingCharacters(in: .whitespaces)