我需要一种方法来删除字符串的第一个字符,这是一个空格。我正在寻找一个方法,甚至是一个扩展的字符串类型,我可以用来削减字符串的字符。
当前回答
斯威夫特4
使用正则表达式的最佳情况:
" this is wrong contained teee xt "
.replacingOccurrences(of: "^\\s+|\\s+|\\s+$",
with: "",
options: .regularExpression)
// thisiswrongcontainedteeext
其他回答
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 trimmedString = string.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
Swift 3 / Swift 4:
let trimmedString = string.trimmingCharacters(in: .whitespaces)
嗨,这可能有点晚,但值得一试。这是一个游乐场的文件。你可以让它成为一个字符串扩展名。
这是在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 "
当你想要删除所有类型的空白时(基于这个SO答案)的正确方法是:
extension String {
var stringByRemovingWhitespaces: String {
let components = componentsSeparatedByCharactersInSet(.whitespaceCharacterSet())
return components.joinWithSeparator("")
}
}
Swift 3.0+ (3.0, 3.1, 3.2, 4.0)
extension String {
func removingWhitespaces() -> String {
return components(separatedBy: .whitespaces).joined()
}
}
EDIT
这个答案是在问题是关于删除所有空白时发布的,问题被编辑为只提到前导空白。如果你只想删除前导空白,请使用以下方法:
extension String {
func removingLeadingSpaces() -> String {
guard let index = firstIndex(where: { !CharacterSet(charactersIn: String($0)).isSubset(of: .whitespaces) }) else {
return self
}
return String(self[index...])
}
}
我会使用这个扩展,以灵活和模仿其他集合如何做到这一点:
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"