在 Swift 中删除字符串开头的所有换行符 [英] Remove all line breaks at the beginning of a string in Swift

查看:41
本文介绍了在 Swift 中删除字符串开头的所有换行符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的字符串:

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?

谢谢

推荐答案

如果可以接受从字符串的两端删除换行符(和其他空白)字符,那么您可以使用>

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*" 匹配字符串开头的所有空格.使用 "^\\n*" 仅匹配换行符.

"^\\s*" matches all whitespace at the beginning of the string. Use "^\\n*" to match newline characters only.

Swift 3 (Xcode 8) 的更新:

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

这篇关于在 Swift 中删除字符串开头的所有换行符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆