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)
3条答案
按热度按时间iih3973s1#
If it is acceptable that newline (and other whitespace) characters are removed from both ends of the string then you can use
To remove leading newline/whitespace characters only you can (for example) use a regular expression search and replace:
"^\\s*"
matches all whitespace at the beginning of the string. Use"^\\n*"
to match newline characters only.Update for Swift 3 (Xcode 8):
kg7wmglp2#
You can use
extension
for TrimEx.
qlfbtfca3#
修剪功能对我不起作用,但这个可以。我只是用空格替换下一行“\n”