我需要一种方法来删除字符串的第一个字符,这是一个空格。我正在寻找一个方法,甚至是一个扩展的字符串类型,我可以用来削减字符串的字符。
当前回答
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: "")
其他回答
嗨,这可能有点晚,但值得一试。这是一个游乐场的文件。你可以让它成为一个字符串扩展名。
这是在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 "
斯威夫特4
使用正则表达式的最佳情况:
" this is wrong contained teee xt "
.replacingOccurrences(of: "^\\s+|\\s+|\\s+$",
with: "",
options: .regularExpression)
// thisiswrongcontainedteeext
这在swift 5中很管用
var myString = " Kwame Ch ef "
myString = myString.replacingOccurrences(of: " ", with: "")
print(myString)
output: Kwame Chef
另一个答案是,有时输入字符串在单词之间可以包含多个空格。如果你需要标准化,单词之间只有一个空格,试试这个(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 !"
代码少做多。
"Hello World".filter({$0 != " "}) // HelloWorld