我需要一种方法来移除字符串中的第一个字符,该字符是空格。我正在寻找一种方法,甚至是String类型的扩展,可以用于从字符串中删除一个字符。
如果您想删除字符串前面(和后面)的空格,但不删除中间的空格,您应该使用 stringByTrimmingCharactersInSet
。
let dirtyString = " First Word "
let cleanString = dirtyString.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
少写代码,多做事。
"Hello World".filter({$0 != " "}) // HelloWorld
以下是另一种解决方案,有时输入的字符串单词之间可能包含多个空格。如果您需要标准化为单词之间只有1个空格,请尝试此方法(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 !"
尝试使用函数式编程来删除空格:
extension String {
func whiteSpacesRemoved() -> String {
return self.filter { $0 != Character(" ") }
}
}
你好,可能有些晚了,但还是值得一试。这是从一个“playground”文件中提取的。你可以将它制作成字符串扩展。
这是使用 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 "
方法二:
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 "
"This is the demo text remove extra space between the words."
,您可以在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."
extension String {
var removingWhitespaceAndNewLines: String {
return removing(.whitespacesAndNewlines)
}
func removing(_ forbiddenCharacters: CharacterSet) -> String {
return String(unicodeScalars.filter({ !forbiddenCharacters.contains($0) }))
}
}
let updatedString = searchedText?.stringByReplacingOccurrencesOfString(" ", withString: "-")
好的,这个问题很旧了,但我自己也遇到过这个问题,除了删除所有空格(这可能会损害应用程序的功能)之外,上面的答案都没有起作用。我的问题如下:
["This", " is", " my", " array", " it is awesome"]
["This", "is", "my", "array", "itisawesome"]
let array = jsonData.components(separatedBy: ",")
To
let array = jsonData.components(separatedBy: ", ")
问题已经解决。希望将来有人能从中受益。
let strFirstName = txtFirstName.text?.trimmingCharacters(in:
CharacterSet.whitespaces)