在Swift中删除字符串开头的所有换行符

igetnqfo  于 2022-12-10  发布在  Swift
关注(0)|答案(3)|浏览(216)

我有这样一个字符串:

"

BLA
Blub"

现在我想删除所有的前导换行符。(但只有那些直到第一个“真实的的单词”出现。这是怎么可能的?)
谢谢

iih3973s

iih3973s1#

If it is acceptable that newline (and other whitespace) characters are removed from both ends of the string then you can use

let string = "\n\nBLA\nblub"
let trimmed = string.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
// In Swift 1.2 (Xcode 6.3):
let trimmed = (string as NSString).stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())

To remove leading newline/whitespace characters only you can (for example) use a regular expression search and replace:

let trimmed = string.stringByReplacingOccurrencesOfString("^\\s*",
    withString: "", options: .RegularExpressionSearch)

"^\\s*" matches all whitespace at the beginning of the string. Use "^\\n*" to match newline characters only.
Update for Swift 3 (Xcode 8):

let trimmed = string.replacingOccurrences(of: "^\\s*", with: "", options: .regularExpression)
kg7wmglp

kg7wmglp2#

You can use extension for Trim

Ex.

let string = "\n\nBLA\nblub"
let trimmed = string.trim()

extension String {
    func trim() -> String {
          return self.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
    }
}
qlfbtfca

qlfbtfca3#

修剪功能对我不起作用,但这个可以。我只是用空格替换下一行“\n”

func removeNextLineString(name: String) -> String{
    var newName = name
    newName = newName.replacingOccurrences(of: "\n", with: " ")
    
    return newName
}

相关问题