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

时间:2022-10-05 22:17:25

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 word" appears. How is this possible?

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

Thanks

谢谢

2 个解决方案

#1


48  

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.

“^ \\ s *”匹配字符串开头的所有空格。使用“^ \\ n *”仅匹配换行符。

Update for Swift 3 (Xcode 8):

更新Swift 3(Xcode 8):

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

#2


6  

You can use extension for Trim

您可以使用Trim的扩展名

Ex.

防爆。

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

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

#1


48  

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.

“^ \\ s *”匹配字符串开头的所有空格。使用“^ \\ n *”仅匹配换行符。

Update for Swift 3 (Xcode 8):

更新Swift 3(Xcode 8):

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

#2


6  

You can use extension for Trim

您可以使用Trim的扩展名

Ex.

防爆。

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

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