我需要一种方法来删除字符串的第一个字符,这是一个空格。我正在寻找一个方法,甚至是一个扩展的字符串类型,我可以用来削减字符串的字符。
当前回答
斯威夫特4
使用正则表达式的最佳情况:
" this is wrong contained teee xt "
.replacingOccurrences(of: "^\\s+|\\s+|\\s+$",
with: "",
options: .regularExpression)
// thisiswrongcontainedteeext
其他回答
另一个答案是,有时输入字符串在单词之间可以包含多个空格。如果你需要标准化,单词之间只有一个空格,试试这个(Swift 4/5)
let inputString = " a very strange text ! "
let validInput = inputString.components(separatedBy:.whitespacesAndNewlines).filter { $0.count > 0 }.joined(separator: " ")
print(validInput) // "a very strange text !"
你也可以使用正则表达式。
let trimmedString = myString.stringByReplacingOccurrencesOfString("\\s", withString: "", options: NSStringCompareOptions.RegularExpressionSearch, range: nil)
如果有人从字符串中删除额外的空格,例如= "这是演示文本,请在单词之间删除额外的空格。"
你可以在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 updatedString = searchedText?.stringByReplacingOccurrencesOfString(" ", withString: "-")
删除字符串中的所有空格:
let space_removed_string = (yourstring?.components(separatedBy: " ").joined(separator: ""))!