Remove all line breaks at the beginning of a string in Swift

后端 未结 2 1744
说谎
说谎 2020-12-03 03:21

I have a string like this:

\"

BLA
Blub\"

Now I would like to remove all leading line breaks. (But only the ones until the first \"real wor

相关标签:
2条回答
  • 2020-12-03 03:40

    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)
        }
    }
    
    0 讨论(0)
  • 2020-12-03 03:44

    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)
    
    0 讨论(0)
提交回复
热议问题